首页 文章

ggplot2:传说中的虚线

提问于
浏览
8

我正在尝试创建一个带有两个叠加密度图的直方图 . 问题是:我希望一个密度是虚线,它完美地工作但在图例中不会出现虚线,如下例所示

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

2 回答

  • 1

    "ggplot"方式通常喜欢数据采用"long"格式,并使用单独的列来指定每个美学 . 在这种情况下,线型应该被解释为美学 . 处理此问题的最简单方法是使用 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

  • 5

    您想要将其重塑为长格式...使其更简单

    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

相关问题