Reputation: 272
library(ggplot2)
library(Hmisc)
data(mtcars)
myplot <- ggplot(mtcars, aes(x = as.factor(cyl), y = qsec)) +
geom_boxplot() +
stat_summary(fun.y = mean, geom = "point", shape = 5, size = 2) +
stat_summary(fun.data = mean_cl_normal, geom = "errorbar",
width = 0.2)
produces
I'd like to dodge the mean and error bars a bit to the right, such that the error bars don't obscure the IQR line of the boxplot. Specifying position=position_dodge(.5)
doesn't seem to work, because geom_errorbar
doesn't know about geom_boxplot
.
Upvotes: 0
Views: 2132
Reputation: 20379
You can introduce a new variable which you use as the x offset for your errorbars:
library(ggplot2)
library(Hmisc)
data(mtcars)
mtcars$cyl.n <- as.numeric(as.factor(mtcars$cyl)) + .5
(myplot <- ggplot(mtcars, aes(x = as.factor(cyl), y = qsec)) +
geom_boxplot() +
stat_summary(aes(x = cyl.n), fun.y = mean, geom = "point", shape = 5, size = 2) +
stat_summary(aes(x = cyl.n), fun.data = mean_cl_normal, geom = "errorbar",
width = 0.2))
The as.numeric(as.factor(.))
makes sure that the new error bar is spaced at the same position as the boxplots but shifted by 0.5 units.
Upvotes: 1