2014-09-10 146 views
1

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

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

当我加入我的错误吧,我从图巴到线匝。虽然它包含错误栏,但我需要一个条形图来恰当地表示我的数据。任何帮助将不胜感激!

+0

,你会不得不看看http://stackoverflow.com/questions/15064462/r-ggplot2-barplot-and-error-bar?谷歌似乎也给出了一些提示,例如http://www.cookbook-r.com/Graphs/Plotting_means_and_error_bars_(ggplot2)/ http://www.r-bloggers.com/using-r-barplot-with-ggplot2/ – lebatsnok 2014-09-10 16:55:05

+0

为什么你从'geom_bar'中删除'stat =“identity”'? – Henrik 2014-09-10 16:56:17

回答

0

尝试:

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) 

enter image description here