【问题标题】:Changing text label color in ggplot bar chart for specific datapoints更改特定数据点的 ggplot 条形图中的文本标签颜色
【发布时间】:2020-07-23 15:56:24
【问题描述】:

我正在尝试使用 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))

这是它生成的情节:

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

谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    执行此操作的更安全的方法是根据将覆盖的填充组分配颜色美学:

    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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-18
      • 2021-07-16
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 2014-04-07
      • 2020-08-01
      相关资源
      最近更新 更多