问题描述
我正在尝试向我的数据添加标准误差线,类似于在该问题答案的结尾附近的方框图中看到的误差线:
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
我正在使用PlantGrowth数据集,它看起来像这样(除了总共30行长):
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
我制作了这个情节
具有以下代码
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
我不知道如何根据该因子变量中的变化为每个图添加误差线.我添加了 + geom_errorbar(aes(x = group,ymin = mean-sd,ymax = mean + sd))
,但它返回错误均值错误-sd:二进制非数值参数运算符"
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
推荐答案
ggplot2中有一个 mean_se
函数,它可以完全满足您的需求.
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")
这篇关于如何使用ggplot2将标准误差线添加到箱形图和晶须图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!