Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - shade area between two vertical lines [duplicate]

Tags:

r

ggplot2

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?

like image 272
P H Avatar asked Feb 07 '12 14:02

P H


2 Answers

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.

like image 90
Brian Diggs Avatar answered Nov 04 '22 14:11

Brian Diggs


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.

like image 39
James Avatar answered Nov 04 '22 12:11

James