Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot errorbar position multi-factor problems

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.

enter image description here

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.

like image 653
slap-a-da-bias Avatar asked Aug 14 '15 22:08

slap-a-da-bias


1 Answers

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)
like image 121
RichAtMango Avatar answered Sep 25 '22 16:09

RichAtMango