Mike
Mike

Reputation: 2097

Conditionally Colouring Bars in Ggplot2

Below is some code for a simple example dataframe and plot. I'm wondering how to conditionally colour the bars. I'm familiar with scale_fill_manual to manually colour the bars, but what if I wanted "Satisfied" in the 2016 facet to be a different colour if it's a lower percentage than "Satisfied" in 2015. Perhaps a red warning border or a different colour, like orange (just for an example).

This isn't the best example, but if I had a plot of year-over-year top box scores, this would be useful to have bars change colour if they dropped below a certain percentage. I tried playing around with "colour = ifelse(Perc < 60, "orange", "green" combinations, but couldn't get it to work. I'm not sure how to structure the ifelse statement or where to place it within the ggplot code.

Year<-c(2015, 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016)

Service<-c("Satisfied", "Satisfied", "Satisfied", "Dissatisfied", "Dissatisfied",
           "Satisfied", "Satisfied", "Dissatisfied", "Dissatisfied", "Dissatisfied")

df <- data.frame(Year, Service)

library(dplyr)
df.prop <- df %>%
            count(Year, Service) %>%
            mutate(Perc = prop.table(n))

library(ggplot2)
ggplot(df.prop, aes(x = Service, y = Perc, fill = Service)) +
       geom_bar(stat = "identity", position = "dodge") +
       geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1),
                 vjust = 1.5, size = 3) +
       scale_y_continuous(labels = percent) +
       facet_grid( ~ Year)

Upvotes: 3

Views: 8732

Answers (1)

erc
erc

Reputation: 10123

Might be easiest to add a new variable to your data frame:

df.prop$colour <- ifelse(df.prop$Service == "Satisfied" & df.prop$Perc < 0.6, "orange", NA)

Then you can do:

ggplot(df.prop, aes(x = Service, y = Perc, fill = Service, colour=colour)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1),
            vjust = 1.5, size = 3, colour="black") +
  scale_y_continuous(labels = percent) +
  facet_grid( ~ Year) +
  scale_colour_identity()

enter image description here

If you want to change the fill based on the condition you can do:

df.prop$fill <- ifelse(df.prop$Service == "Satisfied" & df.prop$Perc < 0.6, "orange", ifelse(df.prop$Service == "Satisfied" & df.prop$Perc >= 0.6, "#00BFC4", "#F8766D"))

ggplot(df.prop, aes(x = Service, y = Perc, fill = fill)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1),
            vjust = 1.5, size = 3) +
  scale_y_continuous(labels = percent) +
  facet_grid( ~ Year) +
  scale_fill_identity()

enter image description here

Upvotes: 6

Related Questions