设置颜色以清晰显示数字

问题描述 投票:0回答:2

在这个特定 viridis 选项的条形图中,是否可以设置颜色,即使对于比例尺的较暗选项,也可以清晰地显示图表内的数字?

library(ggplot2)
Year      <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category  <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data      <- data.frame(Year, Category, Frequency)
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5)) +  scale_fill_viridis_d(option  = "magma")
r ggplot2 colors geom-bar
2个回答
10
投票

利用我从

scales::show_col
学到的一个技巧,你可以根据填充自动选择文本颜色,如下所示:

library(ggplot2)
Year      <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category  <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data      <- data.frame(Year, Category, Frequency)

# Trick from scales::show_col
hcl <- farver::decode_colour(viridisLite::magma(length(unique(Category))), "rgb", "hcl")
label_col <- ifelse(hcl[, "l"] > 50, "black", "white")

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(aes(color = Category), size = 3, position = position_stack(vjust = 0.5), show.legend = FALSE) +  
  scale_color_manual(values = label_col) +
  scale_fill_viridis_d(option  = "magma")

编辑

我最近学到的第二个选项是利用

ggplot2::after_scale
prismatic::best_contrast
自动选择具有最佳对比度的文本颜色,如下所示:

library(prismatic)

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(aes(color = after_scale(
    prismatic::best_contrast(fill, c("white", "black"))
  )),
  size = 3, position = position_stack(vjust = 0.5), show.legend = FALSE
  ) +
  scale_fill_viridis_d(option = "magma")

3
投票

试试这个:

geom_text(...)
替换为
geom_label(fill = "white", ...)
,它会自动提供标签“box”。


library(ggplot2)

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_label(size = 3, position = position_stack(vjust = 0.5), fill = "white") +
  scale_fill_viridis_d(option  = "magma")

reprex 包于 2020-07-08 创建(v0.3.0)

© www.soinside.com 2019 - 2024. All rights reserved.