2012-11-26 191 views
7

我试图创建一个具有两个叠加密度图的直方图。问题是:是我想要一个密度为虚线,这完美的作品,但在传说中的虚线将不会出现,如下面的例子ggplot2:图例中的虚线

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")) 

任何想法如何我得到的虚线传说?

非常感谢!

Example Plot

回答

4

的 “ggplot” 的方式通常喜欢数据能够在“长”格式与分开的专栏来指定每个审美。在这种情况下,线型应该被解释为美学。对付这种最简单的方法是将数据预习到适当的格式reshape2包:

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

然后修改你的绘图代码看起来是这样的:

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") 

在类似结果这个:

enter image description here

+0

+1你可能刚刚提醒我添加库调用大声笑。 –

+0

@BrandonBertelsen - 那完全是两个独立天才的作品......当我试图保存/上传我的答案时,我看到了你的答案和斯蒂芬的作品... – Chase

+0

做那三件事。我们都在几分钟之内贴出了彼此。 –

1

你要重塑这个以长格式...把它简化

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) 
      x   y 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

+0

别蔑视F分布! '?df'也是一个R命令:) – Chase

+0

Gawd ......就这样。我从未注意到。我的代码充满了df。 –

+0

我的太等了,直到有人指出我......这里有一个非常详细的帖子,说明覆盖R函数的名称实际上并不*那*不好,因为R在确定你真正想要的东西时非常聪明做...仍然可能是避免它的最佳实践 - 但4000+不可避免地提供了软件包和更多功能。 – Chase