You can use the following basic syntax to add error bars to a bar plot in R:
ggplot(df) + geom_bar(aes(x=x, y=y), stat='identity') + geom_errorbar(aes(x=x, ymin=y-sd, ymax=y+sd), width=0.4)
The following examples show how to use this function in practice.
Example 1: Add Error Bars Using Summary Data
Suppose we have the following data frame in R that shows the summary statistics for five categories:
#create data frame df frame(category=c('A', 'B', 'C', 'D', 'E'), value=c(12, 17, 30, 22, 19), sd=c(4, 5, 7, 4, 2)) #view data frame df category value sd 1 A 12 4 2 B 17 5 3 C 30 7 4 D 22 4 5 E 19 2
We can use the following code to create a bar plot with error bars to visualize this data:
library(ggplot2) #create bar plot with error bars ggplot(df) + geom_bar(aes(x=category, y=value), stat='identity', fill='steelblue') + geom_errorbar(aes(x=category, ymin=value-sd, ymax=value+sd), width=0.4)
Feel free to use the following arguments to modify the appearance of the error bars:
- width: The width of the error bars
- size: The thickness of the error bars
- color: The color of the error bars
For example:
library(ggplot2) #create bar plot with custom error bars ggplot(df) + geom_bar(aes(x=category, y=value), stat='identity', fill='steelblue') + geom_errorbar(aes(x=category, ymin=value-sd, ymax=value+sd), width=0.3, size=2.3, color='red')
Example 2: Add Error Bars Using Raw Data
Suppose we have the following data frame that shows the raw data for five different categories:
#make this example reproducible set.seed(0) #create data frame df frame(category=rep(c('A', 'B', 'C', 'D', 'E'), each=10), value=runif(50, 10, 20)) #view first six rows of data frame head(df) category value 1 A 18.96697 2 A 12.65509 3 A 13.72124 4 A 15.72853 5 A 19.08208 6 A 12.01682
The following code shows how to summarize the data and then create a bar plot with error bars:
library(dplyr) library(ggplot2) #summarize mean and sd for each category df_summary % group_by(category) %>% summarize(mean=mean(value), sd=sd(value)) #view summary data df_summary # A tibble: 5 x 3 category mean sd 1 A 16.4 2.80 2 B 14.9 2.99 3 C 14.6 3.25 4 D 15.2 2.48 5 E 15.8 2.41 #create bar plot with error bars ggplot(df_summary) + geom_bar(aes(x=category, y=mean), stat='identity', fill='steelblue') + geom_errorbar(aes(x=category, ymin=mean-sd, ymax=mean+sd), width=0.3, color='red')
Additional Resources
The following tutorials explain how to create other common data visualizations in R:
How to Plot Multiple Boxplots in R
How to Plot Multiple Histograms in R
How to Plot Multiple Lines in R