Make the background of a graph different colours in different regions

I wanted to move the line⎯or the bars of the histogram⎯to the foreground, as suggested by baptiste above and fix the background with + theme(panel.background = element_rect(), panel.grid.major = element_line( colour = "white") ), unfortunately I could only do it by sending the geom_bar twice, hopefully someone can improve the code and make the answer complete.

background <- data.frame(lower = seq( 0  , 3  , 1.5 ), 
                         upper = seq( 1.5, 4.5, 1.5 ),
                         col = letters[1:3])
ggplot() + 
    geom_bar( data = mtcars , aes( factor(cyl) ) ) + 
    geom_rect( data = background , 
              mapping = aes( xmin = lower , 
                            xmax = upper ,
                            ymin = 0 ,
                            ymax = 14 ,
                            fill = col ) ,
              alpha = .5 ) + 
    geom_bar(data = mtcars,
             aes(factor(cyl))) +
             theme(panel.background = element_rect(),
                   panel.grid.major = element_line( colour = "white"))

Produces this, geom_bar and geom_rect

Take a look at this site for colour scheme suggestions.


Since you are after vertical (or horizontal) area highlighting, geom_rect() might be an overshoot. Consider geom_ribbon() instead:

ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  geom_ribbon(aes(xmin=3, xmax=4.2), alpha=0.25) +
  theme_minimal()

geom_ribbon


Here's an example to get you started:

#Fake data
dat <- data.frame(x = 1:100, y = cumsum(rnorm(100)))
#Breaks for background rectangles
rects <- data.frame(xstart = seq(0,80,20), xend = seq(20,100,20), col = letters[1:5])


#As Baptiste points out, the order of the geom's matters, so putting your data as last will 
#make sure that it is plotted "on top" of the background rectangles. Updated code, but
#did not update the JPEG...I think you'll get the point.

ggplot() + 
  geom_rect(data = rects, aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf, fill = col), alpha = 0.4) +
  geom_line(data = dat, aes(x,y))

enter image description here

Tags:

R

Ggplot2