Remi.b
Remi.b

Reputation: 18229

ggplot: Boxplot with fill and standard errors

Here is a boxplot

ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + geom_boxplot()

enter image description here

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")

enter image description here

The problem is that the boxed of different colours overlap instead of being side by side.

Upvotes: 0

Views: 1138

Answers (1)

Matthieu P.
Matthieu P.

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')

enter image description here

Upvotes: 3

Related Questions