R: Ggplot2 Barplot and Error Bar

How to plot error bars for grouped bar chart using ggplot2?

You were very close, you need to specify the fill in the ggplot function and not in the geom_bar function.

LabFieldData %>% group_by(Place,Value) %>% 
mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%
#Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
ggplot(mapping = aes(Value, bTemp, color = Place, fill=Place)) +
geom_bar(stat = "summary", position="dodge") +
geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
position=position_dodge(0.9), width=.1, color = "black", size = 1) +
scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35), limits=c(0,34)) +
scale_x_discrete(name=element_blank(), limits=c("Min","Mean","Max")) +
theme(legend.title = element_blank()) + scale_color_hue()

Sample Image

Error plotting the errorbar in the a bar plot created with ggplot2

Here is an approach that relies on two changes:

  1. Plot the error bars first so the bottom half is clipped by the bar
  2. The ymin and ymax values are absolute, not relative, so you need to add or subtract them from the mean.
ggplot(data=descriptives_plot, aes(x=sex.1, y=mean)) +
geom_errorbar(aes(x = sex.1, ymin=(mean-sd), ymax=(mean + sd), width = 0.5)) +
geom_bar(stat = "identity")

Sample Image

Sample data:

descriptives_plot <- structure(list(sex.1 = structure(1:2, .Label = c("Females", "Males"
), class = "factor"), mean = c(14, 24), sd = c(3, 10)), row.names = 1:2, class = "data.frame")

How to organize error bars to relevant bars in a stacked bar plot in ggplot?

You can stack it, but it's hard to read the error bars. @kath made a good point about interpretability. Maybe you want to consider plotting them side by side?

library(gridExtra)

# side by side
side_p <- ggplot(dff, aes(x=month, y=o2, fill=site))+
geom_col(color="black", width=0.6,position=position_dodge(width=0.6))+
geom_errorbar(aes(ymin=o2, ymax=o2+se), width=0.2,position=position_dodge(width=0.6))

# calculate the new y
dff2 = dff %>% arrange(desc(site)) %>% group_by(month) %>% mutate(newy=cumsum(o2))
stacked_p <- ggplot(dff2, aes(x=month, y=o2, fill=site))+
geom_col(color="black", width=0.6,position=position_stack(vjust=1))+
geom_errorbar(inherit.aes = FALSE,aes(x=month,ymin=newy, ymax=newy+se), width=0.2)
#together
grid.arrange(side_p,stacked_p)

Sample Image



Related Topics



Leave a reply



Submit