Change background color on just one region of the graph

background, ggplot2, r

Solution

The rectangle is easy using geom_rect (documentation). You just need to specify it's dimensions in the aes call to geom_rect. To change the transparency alter alpha in the code below.

 require(ggplot2)
 p <- ggplot(mtcars, aes(wt, mpg)) 
 p + geom_point() + 
     geom_rect(aes(xmin = 2, xmax = 4, ymin = -Inf, ymax = Inf),
                   fill = "pink", alpha = 0.03))

Does that produce something like what you're after?

Problem

I would like to change the background color for just a portion of a graph. Is that possible? For example, using the following chart I might want to indicate that I am particularly interested in cars that have a weight between 2 and 4 tons and thus would want to highlight this region using a pink background. More specifically I'd like to overlay a transparent pink rectangle which stretches from 2 to 4 on the x axis and covers the entire y axis region. How would I code this? ``` p <- ggplot(mtcars, aes(wt, mpg)) p + geom_point() ```

Original source

Related problems