Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot variance and confidence interval for variance with ggplot

Consider the variables gear and qsec from the standard data set mtcars.

require(ggplot2)
ggplot(mtcars, aes(x=gear, y=qsec)) + geom_point()

enter image description here

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

enter image description here

Is there an easier solution (like an already implemented function in ggplot2)? If not, can you please confirm that my solution was correct?

like image 952
Remi.b Avatar asked Jul 17 '26 19:07

Remi.b


1 Answers

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

resulting plot

like image 135
Roland Avatar answered Jul 20 '26 12:07

Roland



Donate For Us

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