Aligning error bars for grouped bar chart using ggplot2

Viewed 84

I have a grouped bar chart where the x axis is date. My error bars won't exactly align in the center, even though my position dodge is equal to the width of the bars.

Here is my code:

SZ<- data.frame(Date=rep(c("2021-6-9", "2021-7-7", "2021-8-3", "2021-9-2", "2021-9-30"),3),
                Site=rep(c("SZA", "SZB", "SZC"),each=5),
                Flux=c(2.353333333, 3.33,   4.46,   3.97,   3.2,    1.92,   2.693333333,    4.27,   1.91,   2.536666667,    5.8,    5.776666667,    5.663333333,    3.946666667,    3.216666667
                ),
                sd=c(0.903, 1.453, 0.744, 1.0897, 1.0661, 0.243, 0.481, 0.275, 1.248, 0.501, 1.067, 0.531, 0.818, 0.338, 0.628)
)
head(SZ)

SZ$date <- factor(SZ$Date, levels = unique(SZ$Date))

SZ$date <- as.Date(SZ$date)

p <- ggplot(data=SZ, aes(x=date, y=Flux, fill=Site)) +
  geom_bar(stat="identity", width= 4, position=position_dodge())+
  geom_errorbar(aes(ymin=Flux-sd, ymax=Flux+sd, group=Site), 
                position=position_dodge(4), width = 1, size = 0.3)
p

And here is the output image.

enter image description here

You can probably see best on the second blue bar that it is not centered, but for some of the bars they are centered. I'm wondering if this is an issue with the date formatting of the x axis because there is an unequal number of days in between each sample date. I have also toggled the width and size and that hasn't changed anything. The caps also aren't even, sometimes they only show on one side of the error bar. Any help very much appreciated

0 Answers
Related