[英]Map colors to labels in ggplot based on background color
如何改变 ggplot 中文本的颜色? 例如,我有一个堆叠条形图 plot。我想在背景为浅蓝色或绿色时将标签设为黑色。
这是一个毫无意义的虚拟样本:
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"))
我尝试使用scale_color_manual
,如本例所示( geom_text() 中有超过 1 种颜色),但它没有用。 这个例子中的解决方案甚至对我在问题本身的样本上都不起作用。 也许是因为它已经 8 岁了,idk。
在基于填充颜色的ggplot
调用中动态选择 colors 的解决方案或将“颜色”变量映射到文本 colors 的解决方案都可以。
借用scales::show_col
中的代码片段,根据填充 colors 的亮度将 label colors 设置为“黑色”或“白色”一个选项以实现您想要的结果可能如下所示:
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)
因为你已经有了你想要的 colors,白色和黑色,在mutate
语句中计算,map color = cyl
(与fill
美学相同)并添加具有所需值的scale_color_manual
。
df %>%
ggplot(aes(x = model, y = hwy, fill = cyl)) +
geom_bar(stat = "identity", position = "fill") +
geom_text(aes(color = cyl, label = hwy),
position = position_stack(vjust = 0.5),
show.legend = FALSE) +
scale_fill_manual(name = "cyl",
values = c("dark blue", "light blue", "green"),
breaks = c("4", "6", "8"),
labels = c("4", "6", "8")) +
scale_color_manual(values = c("white", "black", "black"),
breaks = c("4", "6", "8"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.