r - manually adding legend to ggplot with different layer types -
consider graph below created code further below. add legend might "median" , "90% confidence interval." i've seen question partially addressed here (thanks roland), when try implement in own code, legend looks silly because middle line doesn't have fill while ribbon does. there way legend sensible, shows line middle line , fill box ribbon?
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)
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)
first, set guide="none"
scale_fill_manual()
, use function guides()
argument override.aes=
change linetype=
, fill=
according line , 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"))))
Comments
Post a Comment