Search code examples
rggplot2

Set error bars to standard deviation on a ggplot2 bar graph


I have a two-factor bar graph using ggplot2, where I used mean_se to add error bars with the standard error. I would like to use standard deviation instead of standard error.

library(tidyverse)

#load diamonds dataset
diamonds <- diamonds

#two-factor dynamite plot
plt <- ggplot(diamonds, aes(cut, price, fill = color)) +
geom_bar(stat = "summary", fun.y = "mean", position = position_dodge(width = 
0. 9)) +
geom_errorbar(stat = "summary", fun.data = "mean_se", position = 
position_dodge(width = 0.9)) +
ylab("mean price") +
ggtitle("Two-Factor Dynamite plot")

plt

Is there a way to do this similar to using mean_se, but to generate error bars representing one standard deviation? mean_sdl doesn't seem to do this. Thank you.


Solution

  • mean_sdl takes an argument mult which specifies the number of standard deviations - by default it is mult = 2. So you need to pass mult = 1:

    plt <- ggplot(diamonds, aes(cut, price, fill = color)) +
        geom_bar(stat = "summary", fun.y = "mean", 
                 position = position_dodge(width = 0.9)) +
        geom_errorbar(stat = "summary", fun.data = "mean_sdl", 
                      fun.args = list(mult = 1),
                      position =  position_dodge(width = 0.9)) +
        ylab("mean price") +
        ggtitle("Two-Factor Dynamite plot")
    
    plt