Reputation: 123
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.
Upvotes: 2
Views: 1944
Reputation: 497
A simple solution is to define an interval function that goes with the mean. This is done with the package superb
with
library(superb)
library(ggplot2)
#load diamonds dataset
diamonds <- diamonds
# attach an interval function to the mean
SD.mean <- function(x){ sd(x) }
superb(price ~ cut + color, diamonds,
errorbar = "SD"
) +
ylab("mean price") +
ggtitle("Two-Factor Dynamite plot")
We get:
Note that I am the creator of superb
.
Upvotes: 0
Reputation: 60080
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
Upvotes: 3