Consider the variables gear and qsec from the standard data set mtcars.
require(ggplot2)
ggplot(mtcars, aes(x=gear, y=qsec)) + geom_point()

I am trying to plot the within-group variance (for each group) with error bars.
Here is my current solution (using a 95% confidence interval for error bars):
require(data.table)
dtmtcars = data.table(mtcars)[,list(var.qsec = var(qsec)),by=list(gear)]
samplesize = sapply(unique(mtcars$gear), function(x) nrow(subset(mtcars, gear == x)))
high.EB = ((samplesize-1)*dtmtcars$var.qsec)/qchisq(0.025,n-1)
low.EB = ((samplesize-1)*dtmtcars$var.qsec)/qchisq(0.975,n-1)
ggplot(dtmtcars, aes(x=gear, y=var.qsec)) + geom_point() + geom_errorbar(aes(ymin=low.EB, ymax=high.EB))

Is there an easier solution (like an already implemented function in ggplot2)? If not, can you please confirm that my solution was correct?
Use stat_summary. Note that the documentation is wrong when it says that fun.data should "take data frame as input".
ggplot(mtcars, aes(x=gear, y=qsec)) +
stat_summary(fun.y = var, geom = "point") +
stat_summary(fun.data = function(y) {
data.frame(y = var(y),
ymin = ((length(y)-1)*var(y))/qchisq(0.025,length(y)-1),
ymax = ((length(y)-1)*var(y))/qchisq(0.975,length(y)-1))
}, geom = "errorbar") +
ylab("var.qsec")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With