11

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()
zx8754
  • 52,746
  • 12
  • 114
  • 209
Megan
  • 111
  • 1
  • 1
  • 4

2 Answers2

23

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?

Figure attempt

Adam Kimberley
  • 879
  • 5
  • 12
6

Although this works, I noticed that it plots as many rectangles as data points, which might be a problem especially with facetting where the number of points changes between facets. This is reflected by a very low alpha to obtain just approx 50% transparency. I think it's because it uses the data.frame and aesthetics called from ggplot().

One way to avoid that could be calling aes() within geom_point() and create a data.frame specifically for the rectangles. Notice how alpha is much larger but the effect is similar.

require(ggplot2)
ggplot(mtcars) + geom_point(aes(wt, mpg)) + 
geom_rect(data=data.frame(xmin = 2, xmax = 4, ymin = -Inf, ymax = Inf),
    aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), fill="pink", alpha=0.5)

Result enter image description here

Kalamarico
  • 5,466
  • 22
  • 53
  • 70
abreschi
  • 581
  • 6
  • 10