51

I am using ggplot2 to create some fairly simple scatter plots. I currently have two simple vertical lines using:

... + geom_vline(xintercept=159684.186,linetype="dotted",size=0.6)+
geom_vline(xintercept=159683.438,linetype="dotted",size=0.6)+ ...

Can anyone tell me how to shade the area between these two lines from the top of the Y axis to the X axis?

Ramnath
  • 54,439
  • 16
  • 125
  • 152
P H
  • 511
  • 1
  • 4
  • 3

2 Answers2

70

You can use geom_rect.

... + geom_rect(aes(xmin=159683.438, xmax=159684.186, ymin=0, ymax=Inf))

The two values for x come from your geom_vline calls. using ymin=0 takes it down to 0; ymax=Inf will take it all the way to the top of the axis. If you want it to go all the way down to the x axis rather than 0, you can use ymin=-Inf.

Some notes:

This works best if it is early in the order of geoms so that it gets drawn first/below the other parts (especially the scatterplot data).

You can set the fill color (fill aesthetic) outside the aes call to a fixed value. I would also set the transparency (alpha) to something like 0.5 so that the stuff behind it (grid lines, most likely, if you put it as the first geom) can still be seen.

Brian Diggs
  • 57,757
  • 13
  • 166
  • 188
47

It might be even easier to use annotate() for this if you know the coordinates for which region you want to shade. I had some strange rendering problems when I tried to use geom_rect().

library(ggplot2)
data(mtcars)

ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
     annotate("rect", xmin = 3, xmax = 4.2, ymin = 12, ymax = 21,
        alpha = .2)

I know it's essentially the same thing; I just happened stumbled on this tidbit from here.

James
  • 699
  • 8
  • 13
  • 3
    I quite like this approach, as it allow me to have colour and size scales. – Chef1075 Apr 13 '17 at 16:59
  • 1
    Great approach. Multiple `annotate` statement is allowed. As said, `color` and `fill` arguments are easily controlled. `alpha` transparency argument gives nice appearance. – David C. May 28 '17 at 17:57
  • 1
    FYI for full height band, use ymin = -Inf, ymax = Inf – dsg38 Mar 28 '22 at 16:15