根据背景颜色将颜色映射到ggplot中的标签

hmh*_*sen 3 r ggplot2 geom-text

如何改变ggplot中文本的颜色?例如,我有一个堆积条形图。当背景为浅蓝色或绿色时,我想将标签设置为黑色。

这是一个毫无意义的虚拟样本:

library(dplyr)
library(ggplot2)
df <- mpg %>% 
  mutate(cyl = as.character(cyl)) %>% 
  group_by(model, cyl) %>% 
  summarize(hwy = mean(hwy), .groups = "keep") %>% 
  ungroup() %>% 
  group_by(model) %>% 
  mutate(hwy = round(hwy / sum(hwy), 2)) %>% 
  ungroup() %>% 
  head(11) %>% 
  mutate(color = case_when(cyl == "4" ~ "white", 
                           cyl == "6" ~ "black", 
                           cyl == "8" ~ "black"))

df %>% 
  ggplot(data = ., aes(x = model, y = hwy, fill = cyl, label = hwy)) + 
  geom_bar(stat = "identity", position = "fill") + 
  geom_text(color = "white", position = position_stack(vjust = 0.5)) + 
  scale_fill_manual(values = c("dark blue", "light blue", "green"), 
                    name = "cyl",
                    breaks = c("4", "6", "8"),
                    labels = c("4", "6", "8"))
Run Code Online (Sandbox Code Playgroud)

阴谋

我尝试使用scale_color_manual,如本例所示(geom_text() 中超过 1 种颜色),但它不起作用。此示例中的解决方案甚至对我在问题本身的示例中不起作用。也许是因为它已经8岁了,idk。

在调用中根据填充颜色动态选择颜色的解决方案ggplot或将“颜色”变量映射到文本颜色的解决方案都可以。

ste*_*fan 6

借用代码片段,scales::show_col根据填充颜色的亮度将标签颜色设置为“黑色”或“白色”,一个选项可以实现您想要的结果,如下所示:

library(dplyr)
library(ggplot2)
library(carver)

fill_colors <- c("dark blue", "light blue", "green")
# Borrowed from scales::show_col
hcl <- farver::decode_colour(fill_colors, "rgb", "hcl")
label_col <- ifelse(hcl[, "l"] > 50, "black", "white")

df %>% 
  ggplot(data = ., aes(x = model, y = hwy, fill = cyl, label = hwy)) + 
  geom_bar(stat = "identity", position = "fill") + 
  geom_text(aes(color = cyl), position = position_stack(vjust = 0.5), show.legend = FALSE) + 
  scale_fill_manual(values = fill_colors, 
                    name = "cyl",
                    breaks = c("4", "6", "8"),
                    labels = c("4", "6", "8")) +
  scale_color_manual(values = label_col)
Run Code Online (Sandbox Code Playgroud)