How to Use geom_errorbar() Function in ggplot2


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:

How to Change the Legend Title in ggplot2
How to Rotate Axis Labels in ggplot2
How to Adjust Space Between Bars in ggplot2

Leave a Reply

Your email address will not be published. Required fields are marked *