Reputation: 18229
Here is a boxplot
ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + geom_boxplot()
I would like to reproduce the same plot showing the mean, one standard error and two standard errors instead of the median and quantiles.
I did
boxes <- function(x) {
#r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
meanx = mean(x)
n = length(x)
se = sqrt(var(x)/n)
r <- c( meanx-1.96*se, meanx-se, meanx, meanx+se, meanx+1.96*se )
names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
r
}
ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + stat_summary(fun.data=boxes, geom="boxplot")
The problem is that the boxed of different colours overlap instead of being side by side.
Upvotes: 0
Views: 1138
Reputation: 131
position = 'dodge' should solve your problem.
ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + stat_summary(fun.data=boxes, geom="boxplot", position = 'dodge')
Upvotes: 3