How can I use the geom_errorbar() function in ggplot2?

The geom_errorbar() function in ggplot2 allows for the visualization of the variability or uncertainty in data points on a graph. It is typically used to display the standard error, 95% confidence intervals, or other measures of variability around a central point on the graph, such as the mean. This function is particularly useful for comparing groups or conditions and understanding the level of precision in the data. It can be added to a ggplot2 graph by specifying the appropriate variables and aesthetics, such as the x and y coordinates, the upper and lower limits of the error bars, and the width or thickness of the bars.


You can use the geom_errorbar() function in ggplot2 to add error bars to points in a plot.

The following example shows how to use this function in practice.

Example: How to Use geom_errorbar() in ggplot2

Suppose we have the following data frame in R that contains information about points scored by basketball players on various teams:

#create data frame
df = data.frame(team=rep(c('A', 'B', 'C'), each=4),
                points=c(8, 12, 4, 6, 26, 21, 25, 20, 9, 18, 14, 14))

#view data frame
df

   team points
1     A      8
2     A     12
3     A      4
4     A      6
5     B     26
6     B     21
7     B     25
8     B     20
9     C      9
10    C     18
11    C     14
12    C     14

We can use the following syntax to summarize the mean and standard deviation of the points values, grouped by team:

library(dplyr)

#calculate mean and standard deviation of points by team
df_summary <- df %>%
  group_by(team) %>%
  summarise_at(vars(points), list(mean=mean, sd=sd)) %>% 
  as.data.frame()

#view results
df_summary

  team  mean       sd
1    A  7.50 3.415650
2    B 23.00 2.943920
3    C 13.75 3.685557

Next, we can use the following syntax with geom_errorbar() to create a plot that displays the mean value of points for each team with error bars:

library(ggplot2)

#create plot to visualize mean points by team with error bars
ggplot(df_summary, aes(x=team, y=mean)) +
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd))

In this example, the error bars extend one standard deviation above and below the mean value for each team.

If you’d like, you can use geom_point() to add a point to represent the mean points value for each team and you can use the width argument within geom_errorbar() to modify the width of the error bars in the plot:

library(ggplot2)

#create plot to visualize mean points by team with error bars
ggplot(df_summary, aes(x=team, y=mean)) +
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=0.3) +
  geom_point(size=2)

Feel free to increase or decrease the value of the width argument within the geom_errorbar() function to modify the width of the error bars in the plot.

Additional Resources

The following tutorials explain how to perform other common tasks in ggplot2:

x