r – Create a ggplot barplot with differently coloured horizontal rectangles as background

I like Allan Camerons approach best. Here is what I have tried to provide as an alternative using annotations:

library(ggplot2)

ggplot(data, aes(x=name, y=value))+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 0, ymax = 5, fill = "red", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 5, ymax = 10, fill = "green", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 10, ymax = 14, fill = "yellow", alpha = 0.2)+
  annotate("rect", xmin = 0.5, xmax = 4.5, ymin = 14, ymax = 20, fill = "blue", alpha = 0.2) +
  geom_col()+
  scale_x_discrete()+
  geom_text(aes(label=background_area_name), hjust=2.5, vjust=0, angle=90, size=5, color="white") +
  theme_classic()

enter image description here

Read more here: Source link