设置颜色以清晰显示数字

foc*_*foc 5 r colors ggplot2 geom-bar

在这个特定 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")
Run Code Online (Sandbox Code Playgroud)

ste*_*fan 11

利用我学到的一个技巧,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")
Run Code Online (Sandbox Code Playgroud)

编辑

我最近学到的第二个选项是利用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")
Run Code Online (Sandbox Code Playgroud)