Dynamically change color of bars in a bargraph


#1

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.


#2

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

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


#4

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