Search code examples
rggplot2dashboard

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


In order to make a dynamic visualization, for example in a dashboard, I want to display the label colors (percentages or totals) depending on their real values in black or white.

As you can see from my reprex below, I changed the color of the label with the highest percentage manually to black, in order gain a better visability.

Is there a was, to automatically implement the label color? The label with the highest percentage corresponding should always be black, if data is changing over time.

enter image description here

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

Solution

  • you can set the colors using 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()