【问题标题】:R bar graphs with error bars带有误差线的 R 条形图
【发布时间】:2014-09-10 16:38:22
【问题描述】:

我对 R 比较陌生,一直试图弄清楚如何在我的条形图中添加误差线。举一个简单的例子,我有两年的细菌流行数据,我希望添加误差线。首先,我创建了一个数据框,其中包含 x 和 y 值以及具有 95% 置信区间的标准误差:

>df<-data.frame(Year=factor(c(2011,2012)),MS_Prevalence=c(16.02,7.08),se=c(.20750,.10325))

然后我设置误差线的上限和下限:

>limits<-aes(ymax=MS_Prevalence+se,ymin=MS_Prevalence-se)

接下来,我将我的图表设置为 p:

>p<-ggplot(df,aes(y=MS_Prevalence,x=Year))

现在我将条形图添加到图表中:

>p+geom_bar(position="dodge",stat="identity")

我选择条的宽度:

>dodge<-position_dodge(width=0.9)

然后,尝试添加误差线:

>p+geom_bar(position=dodge)+geom_errorbar(limits,position=dodge,width=0.25)

当我添加误差线时,我的图表会从条变为线。虽然它确实包含误差线,但我需要一个条形图来适当地表示我的数据。任何帮助将不胜感激!

【问题讨论】:

标签: r graph standard-error


【解决方案1】:

试试:

ggplot(df) + 
geom_bar(aes(x=Year, y=MS_Prevalence), stat='identity', color=gray)+
geom_errorbar(aes(x=Year, ymin=(MS_Prevalence-se),ymax=(MS_Prevalence+se)),
   width=0.25)

【讨论】: