1

I'm trying to make a barplot in ggplot with three "people" on the x-axis and a proportion on the y. Two of the people will have two bars and the third person will have three. I've successfully grouped the bars correctly, but am having trouble getting error bars to dodge correctly.

I've tried dodging the error bars the same way I did with the bars themselves, but they don't dodge wide enough; they're all clustered toward the center of the group.

library(ggplot2)
#building a fake dataset
person <- c("Person 1", "Person 1", "Person 2", "Person 2", "Person 
            3","Person 3","Person 3")
prop <- as.numeric(c("0.1","0.64","0.43","0.84","0.9","0.23","0.26"))
class <- c("a","b","a","b","a","b","c")
err <- as.numeric(c("0.01","0.01","0.03","0.08","0.01","0.08","0.03"))
dat <- as.data.frame(person)
dat$prop <- prop
dat$class <- class
dat$err <- err
#plotting
p = ggplot(data = dat, aes(x = person, y = prop, fill = class)) +
  geom_bar(stat="identity",position=position_dodge(0.9,preserve='single'),
           colour="black",lwd=1)+
  geom_errorbar(stat='identity',aes(ymin=prop-err, ymax=prop+err),
                position=position_dodge(0.9),width=0.15, size=1)+  
  labs(x="person", y="proportion",fill="class")
p 

enter image description here As you can see if you run that code, the error bars plot correctly onto person 3's bars, but neither of the others. Do I need to add rows to the dataframe to account for the missing data? Or is it an issue with my coding?

Thanks!

OTStats
  • 1,820
  • 1
  • 13
  • 22
hokiehero
  • 11
  • 3

1 Answers1

1

I believe you also need to add the preserve = "single" argument in the position_dodge portion of your geom_errorbar argument.

The code

ggplot(data=dat, aes(x=person, y=prop,fill=class)) + 
  geom_bar(stat="identity",position=position_dodge(0.9,preserve='single'),colour="black",lwd=1) + 
  geom_errorbar(stat='identity',aes(ymin=prop-err, ymax=prop+err), position=position_dodge(0.9, preserve = "single"),width=0.15, size=1) + 
  labs(x="person", y="proportion",fill="class")

gives enter image description here

sumshyftw
  • 1,111
  • 6
  • 14