简体   繁体   中英

ggplot on point estimates and confidence intervals

I am trying to plot the data frame using ggplot that looks like the plot at the bottom of 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))

I tried:

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

I appreciate all the helps.

I just also tried :

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

error message:

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?

Thanks everybody, problem solved:

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

在此处输入图片说明

I'm assuming by "look like" you mean add the ribbons to your graph. If so then the issue is stemming from the Year variable in the a data.frame. It currently has factor class and it needs to be numeric.

If you add this before you call your ggplot graph you should see the ribbons:

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

You could also modify your entire assignment of a to the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM