-2

Consider the graph below that I created with the code further below. I would like to add a legend that might say something like "median" and "90% confidence interval." I've seen this question partially addressed here (thanks Roland), but when I try to implement it in my own code, the legend looks silly because the middle line doesn't have a fill while the ribbon does. Is there some way to get the legend to look sensible, where it shows just a line for the middle line and a fill box for the ribbon?

enter image description here

library(ggplot2)
middle = data.frame(t=c(0,1,2,3),value=c(0,2,4,6))
ribbon = data.frame(t=c(0,1,2,3),min=c(0,0,0,0),max=c(0,4,8,12))
g = ggplot()
g = g + geom_line  (data=middle,aes(x=t,y=value),color='blue',size=2)
g = g + geom_ribbon(data=ribbon,aes(x=t,ymin=min,ymax=max),alpha=.3,fill='lightblue')
print(g)

enter image description here

library(ggplot2)
middle = data.frame(t=c(0,1,2,3),value=c(0,2,4,6))
ribbon = data.frame(t=c(0,1,2,3),min=c(0,0,0,0),max=c(0,4,8,12))
g = ggplot()
g = g + geom_ribbon(data=ribbon,aes(x=t,ymin=min,ymax=max,fill="CI" ,color="CI"))
g = g + geom_line  (data=middle,aes(x=t,y=value,                     color="median"))
g = g + scale_colour_manual(values=c("lightblue","blue"))
g = g + scale_fill_manual  (values=c("lightblue"))
print(g)
Community
  • 1
  • 1
Andy Stein
  • 461
  • 1
  • 4
  • 11
  • 1
    If you want a legend, map a values to `color` and `fill` inside `aes` and use `scale_color_manual` and `scale_fill_manual` to specify labels and colors. – Roland Feb 05 '16 at 19:32
  • Hi Roland, the answer to the hold question only sort of helped. I tried implementing it (see above), but the legend looks really silly. Is there some way to get this legend to look sensible? – Andy Stein Feb 06 '16 at 17:11

1 Answers1

1

First, set guide="none" for the scale_fill_manual() and then use function guides() with argument override.aes= to change linetype= and fill= according to line and confidence interval.

ggplot() + 
  geom_ribbon(data=ribbon,aes(x=t,ymin=min,ymax=max,fill="CI" ,color="CI")) + 
  geom_line(data=middle,aes(x=t,y=value,color="median"))+ 
  scale_colour_manual("Legend",values=c("lightblue","blue")) + 
  scale_fill_manual(values=c("lightblue"),guide="none")+
  guides(colour = guide_legend(override.aes = list(linetype=c(0,1),fill=c("lightblue","white"))))

enter image description here

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • Thanks Didzis. If anyone knows a more efficient way to do this, that'd be great. It seems then for graphs like this, ggplot is really not the right plotting environment, just because in other environments, you can get a legend with a single, simple line of code instead of needing multiple lines where you have to specify both the color of the lines and the again, the color of everything in the legend. – Andy Stein Feb 06 '16 at 19:28