Thursday, 22 August 2013

R: Custom Legend for Multiple Layer ggplot

R: Custom Legend for Multiple Layer ggplot

I'm trying to get a custom legend for a ggplot with data coming from two
separate data frames. See below for a minimum reproducible example.
What I'm trying to accomplish is to have a legend describing the ribbon
fill, the black line, and the red line.
require(ggplot2)
x=seq(1,10,length=100)
data=data.frame(x,
dnorm(x,mean=5,sd=1)+.01,
dnorm(x,mean=5,sd=1)-.01,
dnorm(x,mean=5,sd=1),
dnorm(x,mean=5.5,sd=1))
names(data)=c('x','max','min','avg','new.data')
ggplot()+geom_ribbon(data=data,aes(ymin=min,ymax=max,x=x),fill='lightgreen')+
geom_line(data=data,aes(x=x,y=avg),color='black')+
geom_line(data=data,aes(x=x,y=new.data),color='red')+
xlab('x')+ylab('density')

In my full dataset, the data from the geom_ribbon comes from a different
data frame.

No comments:

Post a Comment