Bar Graph with Error Bars in R
The Ggplot2 package can be used to create a bar graph with error bars. The geom_bar() function can be used to create the bar graph, and geom_errorbar() function can be used to add error-bars on the bar graph. We will use the dummy dataset (d_apples) below to create an example of a bar graph with error-bars.
The dummy dataset contains the average number of kilograms of apples sold per month in a certain supermarket. We will use the variable mean_kg to create the bar graph, and ci95ll and ci95ul to add 95% confidence intervals to the bar graph.
Horizontal Bar Graph with Error Bars
First, we order the months of the year from January to May to avoid showing them alphabetically. Then we create the bar graph before adding the error-bars on top of the bar graph:
#order the months from January to May instead of alphabetically
d_apples$month2 <- fct_reorder(d_apples$Month, seq(1,5))
#create horizontal bar graph
b <- ggplot(data=d_apples, aes(x=month2, y=mean_kg, fill=Month)) +
geom_bar(stat="identity", width=0.4) +
labs(y = "Mean # of Appels Sold (kg)", x = "Month", fill = "Months") +
#rotate the x-axis values 45 degrees to avoid overlapping
theme(axis.text.x= element_text(angle=45, vjust=1, hjust=1))
b
#adding the error-bars
c <- b + geom_errorbar(aes(ymin = ci95ll, ymax = ci95ul), width = 0.1)
c
Vertical Bar Graph with Error Bars
Finally let’s flip the y-axis and x-axis to create a horizontal bar graph with error-bars.
The function coord_flip() flips the axes to create horizontal bars without the need to change any of the previous code.
#flip axes to horizontal bars
d <- c + coord_flip()
d