21

I have manually created a data set of life expectancies with accompanying 95% confidence bands. I plot these over the time scale but would prefer the bands to be shaded rather than dotted lines. Code shown:

p1 = ggplot()
p2 = p1 + geom_line(aes(x=pl$Time, y=pl$menle), colour="blue")
p3 = p2 + geom_line(aes(x=pl$Time, y=pl$menlelb), colour="blue", lty="dotted")
p4 = p3 + geom_line(aes(x=pl$Time, y=pl$menleub), colour="blue", lty="dotted")

Is there a simple way to shade the interval rather than just have the lines?? If I'm missing something simple I apologise in advance but I cannot find anything to indicate a simple way of doing this.

stats4ever
  • 431
  • 1
  • 3
  • 5
  • 4
    Use `geom_ribbon` instead. – joran May 09 '13 at 13:51
  • 2
    And please provide data for others to try your code (or use data that's available with R). – Arun May 09 '13 at 13:52
  • 2
    Note that if you're using `$` in ggplot, you're probably doing it wrong -- also known as the adage: "ggplot2 doesn't care for `$`, it feeds on `data`". – baptiste May 09 '13 at 14:31

1 Answers1

55

It would be helpful if you provided your own data, but I think the following does what you are after.

First, create some dummy data:

##I presume the lb and ub are lower/upper bound
pl = data.frame(Time = 0:10, menle = rnorm(11))
pl$menlelb = pl$menle -1
pl$menleub = pl$menle +1

Then create the plot. The shaded region is created using geom_ribbon:

ggplot(pl, aes(Time)) + 
  geom_line(aes(y=menle), colour="blue") + 
  geom_ribbon(aes(ymin=menlelb, ymax=menleub), alpha=0.2)

enter image description here

csgillespie
  • 59,189
  • 14
  • 150
  • 185
  • 1
    If I plot two or more sets of geom_line(...) + geom_ribbon(...) for same x but different y, ymin, ymax, how can I add a legend/label? – jf328 Oct 20 '15 at 14:08