ggplot2:图例中的虚线 [英] ggplot2: Dashed Line in legend
问题描述
我试图创建一个具有两个叠加密度图的直方图。问题是:我想要一个密度是一条虚线,它完美地工作,但在图例中虚线不会出现,如下例所示:
x <-sort(rnorm(1000))
data <-data.frame(x = x,Normal = dnorm(x,mean(x),sd = sd(x)) ,学生= 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值= c(学生=黑色,普通=黑色))
任何想法我如何得到传说中的虚线?
非常感谢!
Rainer
$ b
ggplot方式通常喜欢数据以长格式与分隔符te列来指定每种美学。在这种情况下,线型应该被解释为美学。处理这个问题的最简单方法是用 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)
结果如下:
I'm trying to create a histogram with two superimposed density plots. The problem: is I want one density to be a dashed line, which works perfectly 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?
Thank you very much!
Rainer
The "ggplot" way generally likes data to be in "long" format with separate columns to specify each aesthetic. In this case, linetype should be interpreted as an aesthetic. The easiest way to deal with this is to prep your data into the appropriate format with reshape2
package:
library(reshape2)
data.m <- melt(data, measure.vars = c("Normal", "Student"), id.vars = "x")
And then modify your plotting 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")
Results in something like this:
这篇关于ggplot2:图例中的虚线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!