0

I'd like to create a graph that looks like this, but uses my own data for the min/max of the grey fit line enter image description here

Here is a simple plot.

df <- data.frame(x1 = c(0,1,2,3,4),
                 y1 = c(2,3,4,5,6),
                 x2 = c(0,1,2,3,4),
                 y2 = c(3,4,6,7,8),
                 x3 = c(0,1,2,3,4),
                 y3 = c(0,0,1,2.5,2))

g <- ggplot(data=df) +
  geom_line(aes(x1,y1,color="red")) + 
  geom_line(aes(x2,y2)) +
  geom_line(aes(x3,y3))

enter image description here

I want a transparent grey fill area like in the example to be behind the red line and between the 2 black lines. How do I accomplish this?

njfrazie
  • 91
  • 1
  • 14
  • "That" line is a (so called) [loess regression](https://en.wikipedia.org/wiki/Local_regression), with your data you won't have a line like that. Try but just adding `g + stat_smooth(aes(x3, y3))` you'll see that it is not like you would expect. – SabDeM Aug 17 '15 at 17:32
  • The answer to http://stackoverflow.com/questions/26020142/adding-shade-to-r-lineplot-denotes-standard-error gives a very nice example. – bdecaf Aug 17 '15 at 17:36
  • To expand on @joran's comment, after the call to `ggplot` and before the calls to `geom_line` add something like this: `geom_ribbon(aes(x=x1, ymin=y3, ymax=y2), fill="grey60", alpha=0.5) +` – eipi10 Aug 17 '15 at 17:54
  • @joran, is there any reason to recommend geom_ribbon over geom_polygon since the OP isn't using smoothed data (though the example the use is obviously smoothed) – scribbles Aug 17 '15 at 18:05
  • @scribbles IMHO yes, as I view `geom_ribbon` as a special case of `geom_polygon` (they both end up calling `grid::polygonGrob`.) that is specifically intended for a single set of x values and a set of upper/lower y values. `geom_polygon` in my mind is more for drawing arbitrary shapes. – joran Aug 17 '15 at 19:10

1 Answers1

2

You can use the polygon function for this.

x <- 1:50
y_low <- rnorm(length(x), 150, 25) + 5*x
y_high <- rnorm(length(x), 250, 25) + 5*x

plot(x, y_high, type='l', ylim = c(000, 600))    
polygon(c(x, rev(x)), c(y_high, rev(y_low)), col = "grey40")

enter image description here

Another option (as mentioned in the comments) is to add the geom_ribbon attribute. You can specify customer values for the interval. The following did the work:

g <- ggplot(data=df) + geom_ribbon(aes(x=x1, ymin=y2, ymax=y3)) 
   + geom_line(aes(x1,y1,color="red")) 
   + geom_line(aes(x2,y2)) + geom_line(aes(x3,y3))

enter image description here

  • The OP provides a code (and a figure) for `ggplot2` so it is very unlikely that he/she wants to switch to a base R solution. – SabDeM Aug 17 '15 at 17:33