如何根据相对值(maximum/minimum)自动更改标签颜色?

How to automatically change label color depending on relative values (maximum/minimum)?

为了进行动态可视化,例如在仪表板中,我想根据标签颜色(百分比或总计)的实际值以黑色或白色显示。

从我下面的 reprex 可以看出,我手动将百分比最高的标签颜色更改为黑色,以获得更好的可见性。

有没有自动实现标签颜色的方法?如果数据随时间变化,对应百分比最高的标签应始终为黑色。

library(ggplot2)
library(dplyr)

set.seed(3)
reviews <- data.frame(review_star = as.character(sample.int(5,400, replace = TRUE)),
                      stars = 1)

df <- reviews %>% 
  group_by(review_star) %>% 
  count() %>% 
  ungroup() %>% 
  mutate(perc = `n` / sum(`n`)) %>% 
  arrange(perc) %>%
  mutate(labels = scales::percent(perc))

ggplot(df, aes(x = "", y = perc, fill = review_star)) +
  geom_col(color = "black") +
  geom_label(aes(label = labels), color = c( "white", "white","white",1,"white"),
             position = position_stack(vjust = 0.5),
             show.legend = FALSE) +
  guides(fill = guide_legend(title = "Answer")) +
  scale_fill_viridis_d() +
  coord_polar(theta = "y") + 
  theme_void()

您可以使用 replace(rep('white', nrow(df)), which.max(df$perc), 'black') 设置颜色。

ggplot(df, aes(x = "", y = perc, fill = review_star)) +
  geom_col(color = "black") +
  geom_label(aes(label = labels), 
             color = replace(rep('white', nrow(df)), which.max(df$perc), 'black'),
             position = position_stack(vjust = 0.5),
             show.legend = FALSE) +
  guides(fill = guide_legend(title = "Answer")) +
  scale_fill_viridis_d() +
  coord_polar(theta = "y") + 
  theme_void()