2

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()
tjebo
  • 21,977
  • 7
  • 58
  • 94
Leonhard Geisler
  • 506
  • 3
  • 15
  • related https://stackoverflow.com/questions/49716005/how-to-control-label-color-depending-on-fill-darkness-of-bars and first I thought it was a duplicate of https://stackoverflow.com/questions/49437263/contrast-between-label-and-background-determine-if-color-is-light-or-dark?noredirect=1&lq=1, but you were asking to set the maximum value in black, I overlooked that – tjebo Feb 07 '22 at 14:35

1 Answers1

2

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()
dww
  • 30,425
  • 5
  • 68
  • 111