Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading