Ggplot2: dashed line in the legend

I am trying to create a histogram with two superimposed density plots. Problem: I want one density to be a dashed line that works fine, but in the legend the dashed line will not appear, as in the following example

x<-sort(rnorm(1000)) data<-data.frame(x=x,Normal=dnorm(x,mean(x),sd=sd(x)),Student=dt(x,df=3)) ggplot(data,aes(y=x))+geom_histogram(aes(x=x,y=..density..), color="black",fill="darkgrey")+geom_line(aes(x=x,y=Normal,color="Normal"),size=1, linetype=2)+ylab("")+xlab("")+labs(title="Density estimations")+geom_line(aes(x=x,y=Student,color="Student"),size=1)+ scale_color_manual(values=c("Student"="black","Normal"="black")) 

Any ideas how I get the dashed line in the legend?

Many thanks!

Rainer

Example plot

+7
source share
2 answers

"ggplot" usually likes the data to be in a "long" format with separate columns to indicate every aesthetic. In this case, the type of line should be interpreted as aesthetic. The easiest way to handle this is to prepare your data in the appropriate format using the reshape2 package:

 library(reshape2) data.m <- melt(data, measure.vars = c("Normal", "Student"), id.vars = "x") 

And then change your build code to look something like this:

 ggplot(data,aes(y=x)) + geom_histogram(aes(x=x,y=..density..),color="black",fill="darkgrey") + geom_line(data = data.m, aes(x = x, y = value, linetype = variable), size = 1) + ylab("") + xlab("") + labs(title="Density estimations") 

The result is something like this:

enter image description here

+4
source

You want to reformat this to a long format ... simplifies

 x<-sort(rnorm(1000)) Normal=dnorm(x,mean(x),sd=sd(x)) Student=dt(x,df=3) y= c(Normal,Student) DistBn= rep(c('Normal', 'Student'), each=1000) # don't call it 'data' that is an R command df<-data.frame(x=x,y=y, DistBn=DistBn) head(df) xy DistBn 1 -2.986430 0.005170920 Normal 2 -2.957834 0.005621358 Normal 3 -2.680157 0.012126747 Normal 4 -2.601635 0.014864165 Normal 5 -2.544302 0.017179353 Normal 6 -2.484082 0.019930239 Normal ggplot(df,aes(x=x, y=y))+ geom_histogram(aes(x=x,y=..density..),color="black",fill="darkgrey")+ geom_line(aes(x=x,y=y,linetype=DistBn))+ ylab("")+xlab("")+labs(title="Density estimations")+ scale_color_manual(values=c("Student"="black","Normal"="black")) 

Rplot

+1
source

All Articles