Home > Software engineering >  ggplot geom_errorbar not on the bars?
ggplot geom_errorbar not on the bars?

Time:07-04

My dataset looks like this:

df<-data.frame(Mean=c(56.0,63.8,46.9,48.5,39.8, 44.4, 51.9, 57.2, 40.5, 40.6),
              sd=c(24.0, 21.8, 24.4, 24.0, 21.0, 19.8, 22.4, 21.5, 20.5, 15.6),
              Quality=as.factor(c("P","M","P","M",
                                  "P","M", "P","M",
                                  "P","M")), 
              Category=c("A","B","C","D","E"),
              Insert= c(0.0, 0.1, 0.3, 0.5, 1.0))

Upon plotting, I get the following figure: enter image description here

Basically, the error bars are not on the bars but are presented between the bars. Kindly let me know how can I correct the error bars so that they appear on the bars.

I use the following code:

p <- ggplot(df, aes(x=Category, y=Mean, fill=Quality))  
  geom_bar(position=position_dodge(), stat="identity",
           colour='black')   
  geom_errorbar(aes(ymin=Mean-sd, ymax=Mean sd), width=.2)
print(p)

CodePudding user response:

To achieve your desired result you also have to dodge the error bars by using position=position_dodge(.9) where the .9 refers to the default width by which the bars get dodged:

library(ggplot2)

ggplot(df, aes(x=Category, y=Mean, fill=Quality))  
  geom_bar(position=position_dodge(), stat="identity",
           colour='black')   
  geom_errorbar(aes(ymin=Mean-sd, ymax=Mean sd), width=.2, position=position_dodge(.9))

  • Related