Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add standard error bars to a box and whisker plot using ggplot2?

Tags:

graph

r

ggplot2

I'm trying to add standard error bars to my data similar to the ones seen on the box plots near the end of the answer on this question: https://stats.stackexchange.com/questions/8137/how-to-add-horizontal-lines-to-ggplot2-boxplot

I am using the PlantGrowth dataset, which looks like this (except 30 rows long in total):

    weight    group
1   4.17      ctrl
2   5.58      ctrl
3   4.81      trt1
4   4.17      trt1
5   6.31      trt2
6   5.12      trt2

I have produced this plot

this plot

with the following code

 ggplot(PlantGrowth, aes(group, weight))+
stat_boxplot(geom='errorbar', linetype=1, width=0.5)+  #whiskers
geom_boxplot(outlier.shape=1)+    
stat_summary(fun.y=mean, geom="point", size=2)   #dot for the mean

I don't know how to add an error bar for each plot based on the variation within that factor variable. I have added +geom_errorbar(aes(x=group, ymin=mean-sd, ymax=mean+sd)) but it returns the error "Error in mean - sd : non-numeric argument to binary operator"

Any help would be appreciated. Thank you

like image 401
Jennser Avatar asked Jul 26 '16 20:07

Jennser


People also ask

How do you add standard error bars in Boxplot R?

Error bars can be added to plots using the arrows() function and changing the arrow head. You can add vertical and horizontal error bars to any plot type. Simply provide the x and y coordinates, and whatever you are using for your error (e.g. standard deviation, standard error).

Do box and whisker plots have error bars?

For the lines in a box and whisker plot: error bars are the 95% confidence interval, the bottom and top of the box are the 25th and 75th percentiles, the line inside the box is the 50th percentile (median), and any outliers are shown as open circles.

What are error bars in ggplot2?

Error bars are used to show the range of uncertainty around the distribution of data. We can draw error bars to a plot using the geom_errorbar() function of the ggplot2 package of the R Language. Syntax: plot + geom_errorbar( aes( ymin= value – standard_error, ymax= value + standard_error ))

How do I make Ggplot error bars smaller?

Specify ymin = len-sd and ymax = len+sd to add lower and upper error bars. If you want only to add upper error bars but not the lower ones, use ymin = len (instead of len-sd ) and ymax = len+sd .


1 Answers

There is a mean_se function in ggplot2 which does exactly what you want.

library(ggplot2)
ggplot(PlantGrowth, aes(group, weight))+
  stat_boxplot( aes(group, weight), 
    geom='errorbar', linetype=1, width=0.5)+  #whiskers
  geom_boxplot( aes(group, weight),outlier.shape=1) +    
  stat_summary(fun.y=mean, geom="point", size=2) + 
  stat_summary(fun.data = mean_se, geom = "errorbar")
like image 72
shayaa Avatar answered Oct 12 '22 22:10

shayaa