Dynamically change color of bars in a bargraph

How to change the color of a particular bar based on a particular threshold...

Say I am dividing revenue for a few department but I want to change the color of the bar of a particular or multiple department they meet a particular criteria.

Please tell me how should I do it.

There's more than one way to do this, but here's one approach:

library(tidyverse)

bar_data <- mtcars %>%
  group_by(cyl) %>%
  summarize(hp_mean = mean(hp)) %>%
  mutate(hilite = hp_mean > quantile(hp_mean, 0.75))

ggplot(bar_data) +
geom_col(aes(
  x = factor(cyl),
  y = hp_mean,
  fill = hilite
)) +
scale_fill_manual(name = "Performance",
  values = c("TRUE" = "red", "FALSE" = "grey50"),
  labels = c("TRUE" = "Double-plus good", "FALSE" = "Just OK")
)

hilite_bar

3 Likes

thanks again for such an elegant solution I understood it at one go. Now I know how to proceed. Thanks again.

Great solution @jcblum, cannot resist to add that IMHO one should avoid generating data in the call to ggplot, but rather include all the data needed for plotting in the data itself and also if possible set the aesthetics in the ggplot call :slightly_smiling_face:

bar_data = mtcars %>%
  group_by(cyl) %>%
  summarize(hp_mean = mean(hp)) %>%
  mutate(hilite = ifelse(hp_mean > quantile(hp_mean, 0.75),
                         "Double-plus good", "Just OK"))
bar_data %>%
  ggplot(aes(x = factor(cyl), y = hp_mean, fill = hilite)) +
  geom_col()
1 Like