I've been trying to plot standard error bars over a multilevel histogram of data that is very similar to the following:
mth<-rep(c("June","July","August"),length.out=15)
yr<-rep(c("1999","2000","2005","2009","2010"),each=3)
X<-rnorm(15,mean=200,sd=100)
lng<-rep(c(30,31,31),length.out=15)
vrnc<-rnorm(15,mean=740,sd=300)
df<-data.frame(mth,yr,vrnc,lng,X)
dfi<-dim(df)[1]
for(i in 1:dfi){
df$X.se[i]<-sqrt(df$vrnc[i]/df$lng[i])
}
I've tried placing error bars using the stat_summary method described in this thread. My code with stat_summary looks like this:
ggplot(df,aes(x=yr,y=X,fill=mth))+
stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) +
stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
color="grey40",position=position_dodge(1), width=.2) +
geom_errorbar(data=df,aes(ymin=X-X.se,ymax=X+X.se,position="dodge",width=.2))+
scale_fill_discrete("mth")
I've also tried using this code:
ggplot(df,aes(x=yr,y=X,fill=mth))+
geom_bar(stat="identity",position="dodge")+
geom_errorbar(data=df,aes(ymin=X-X.se,ymax=X+X.se,position="dodge",width=.2))
but the result always comes out with the error bars all in the middle of each year.
I'd like to know what I'm doing wrong. each error bar should be on top of the month/year referenced in the data.
had to do this recently. something like:
ggplot(df,aes(x=yr,y=X,fill=mth))+
geom_bar(stat="identity", position = position_dodge()) +
geom_errorbar(aes(ymin=X-X.se, ymax=X+X.se), position = position_dodge(.9), width=.2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With