我正在尝试创建一个带有两个叠加密度图的直方图.问题是:我希望一个密度是虚线,它完美地工作但在图例中不会出现虚线,如下例所示
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"))
Run Code Online (Sandbox Code Playgroud)
我是如何获得传奇中的虚线的?
非常感谢你!
莱纳

"ggplot"方式通常喜欢数据为"长"格式,并使用单独的列来指定每个美学.在这种情况下,线型应该被解释为美学.处理此问题的最简单方法是使用reshape2包将数据准备为适当的格式:
library(reshape2)
data.m <- melt(data, measure.vars = c("Normal", "Student"), id.vars = "x")
Run Code Online (Sandbox Code Playgroud)
然后修改您的绘图代码,看起来像这样:
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")
Run Code Online (Sandbox Code Playgroud)
结果是这样的:

| 归档时间: |
|
| 查看次数: |
4666 次 |
| 最近记录: |