在ggplot条形图中更改特定数据点的文本标签颜色

VCM:

我正在尝试使用ggplot2更改与条形图中的特定数据点关联的文本标签的颜色。

这是原始代码-以mtcars为例:

mtcars_gear_percentage_by_make <- mtcars %>%
  tibble::rownames_to_column(var = "car") %>%
  tidyr::separate(car, c("make", "model"), sep = "\\s") %>%
  dplyr::filter(make == "Merc" | make == "Toyota") %>%
  dplyr::group_by(make, gear) %>%
  dplyr::summarize(n_model = n()) %>%
  dplyr::mutate(percentage_gear = n_model / sum(n_model, na.rm = TRUE))

ggplot(mtcars_gear_percentage_by_make,
       aes(x = make, y = percentage_gear, fill = gear, label = round(percentage_gear, 2))) +
  geom_col() +
  geom_label(position = position_stack(vjust = 0.5))

这是它生成的图:

齿轮型号百分比

有没有办法将深蓝色部分中的文本标签的颜色更改为白色,而使浅蓝色部分中的文本标签的颜色保持不变?

谢谢!

艾伦·卡梅隆(Allan Cameron):

一种更安全的方法是根据将要覆盖的填充组分配颜色美感:

ggplot(mtcars_gear_percentage_by_make,
       aes(x = make, y = percentage_gear, fill = gear, label = round(percentage_gear, 2))) +
  geom_col() +
  geom_label(aes(colour = gear),
             position = position_stack(vjust = 0.5)) +
  scale_color_gradient(low = "white", high = "black", guide = guide_none())

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章