关于点估计和置信区间的ggplot

时间:2015-05-28 15:29:29

标签: r ggplot2

我正在尝试使用ggplot来绘制数据框,这看起来像http://www.ats.ucla.edu/stat/r/dae/logit.htm底部的情节。

       a<-data.frame(Year=c("2012","2012","2012","2013","2013","2013","2014","2014","2014"),
          Engagement=rep(c("low","med","high"),3),
         cost=c(4464.88,4690.14,4342.72,5326.63,5000.03,3967.02,4646.27,4282.38,3607.79),
         lower=c(4151.4,5027.51,4095.73,4366.82,4682.85,3715.86,3775.25,3642.41,3235.43),
         upper=c(4778.35,5625.75,5196.81,5013.45,5317.2,4848.89,4910.19,4291.64,3980.14))

我试过了:

k<-ggplot(a,aes(x=Year,y=cost))
k+geom_ribbon(aes(ymin=lower,ymax=upper,fill=Engagement),alpha=0.2)+
geom_pointrange(aes(x=Year,y=cost,ymin=lower,ymax=lower),size=1,width=0.2,color="blue")

我感谢所有的帮助。

我也尝试过:

pd <- position_dodge(0.1)
k<-ggplot(a,aes(x=Year,y=cost))
k+geom_ribbon(aes(ymin=lower,ymax=upper,fill=Engagement),alpha=0.2)+
  geom_line(position=pd,aes(color=Engagement))

错误消息:

ymax not defined: adjusting position using y instead
geom_path: Each group consist of only one observation. 
Do you need to adjust the group aesthetic?

2 个答案:

答案 0 :(得分:1)

谢谢大家,问题解决了:

k+geom_line(aes(group=Engagement,color=Engagement))+
  geom_errorbar(aes(ymin=lower,ymax=upper,color=Engagement,width=0.2))

enter image description here

答案 1 :(得分:0)

我假设“看起来像”你的意思是在图表中添加色带。如果是这样,则问题源于Year data.frame中的a变量。它目前有因子类,它需要是数字。

如果你在调用ggplot图之前添加它,你应该看到色带:

a$Year <- as.numeric(a$Year)

您还可以将a的整个作业修改为以下内容:

a<-data.frame(Year=as.numeric(c("2012","2012","2012","2013","2013","2013","2014","2014","2014")),
              Engagement=rep(c("low","med","high"),3),
              cost=c(4464.88,4690.14,4342.72,5326.63,5000.03,3967.02,4646.27,4282.38,3607.79),
              lower=c(4151.4,5027.51,4095.73,4366.82,4682.85,3715.86,3775.25,3642.41,3235.43),
              upper=c(4778.35,5625.75,5196.81,5013.45,5317.2,4848.89,4910.19,4291.64,3980.14))