【问题标题】:Set a color to show clear the numbers设置颜色以显示清晰的数字
【发布时间】:2020-10-29 05:16:45
【问题描述】:

在这个特定 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


【解决方案1】:

利用我从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_scaleprismatic::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")

【讨论】:

  • 很好的解决方案,它不会像geom_labelggtext::geom_textbox 那样搞乱定位,往往与position_stack...
【解决方案2】:

试试这个:

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


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 package (v0.3.0) 于 2020-07-08 创建

【讨论】:

  • 请用简单的英语评论一下你做了什么。
  • 请注意,如果您对fill 使用静态值,则可以在aes 之外调用它。
猜你喜欢
  • 2022-01-17
  • 2018-01-20
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-24
相关资源
最近更新 更多