Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background bands with ggplot in R

Tags:

r

ggplot2

I'm trying to create box plots for different groups. I'd like to color the background in 3 horizontal bands. A central one where there are all the observations that are near the overall mean

mean(weight)-0.5 < x < mean(weight)+0.5

The other 2 bands are the below and the upper ones.

Theese are my plot

library(ggplot2)
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
bp
like image 743
dax90 Avatar asked Apr 26 '15 12:04

dax90


1 Answers

Use geom_rect:

bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) +
    geom_rect(ymin = -Inf, ymax = lwWt, 
              xmin = -Inf, xmax = Inf, fill = 'blue') +
    geom_rect(ymin = lwWt, ymax = upWt, 
              xmin = -Inf, xmax = Inf, fill = 'pink') + 
    geom_rect(ymin = upWt, ymax = Inf, 
          xmin = -Inf, xmax = Inf, fill = 'skyblue') +
    geom_boxplot() 
print(bp)
ggsave("example.jpg", bp)

Which gives you this figure:enter image description here

Hopefully you'll change the background colors :)

like image 124
Richard Erickson Avatar answered Oct 29 '22 21:10

Richard Erickson