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