像这样的东西吗?
library(ggplot2)
get.se <- function(y) {
se <- sd(y)/sqrt(length(y))
mu <- mean(y)
c(ymin=mu-se, ymax=mu+se)
}
ggplot(df1, aes(x=site, y=V1)) +
stat_summary(fun.y=mean, geom="bar", fill="lightgreen", color="grey70")+
stat_summary(fun.data=get.se, geom="errorbar", width=0.1)
ggplot(df2, aes(x=site, y=V1, fill=when)) +
stat_summary(fun.y=mean, geom="bar", position="dodge", color="grey70")+
stat_summary(fun.data=get.se, geom="errorbar", width=0.1, position=position_dodge(width=0.9))
所以这利用了stat_summary(...)
ggplot 中的函数首先总结y
对于给定的x
using mean(...)
(对于酒吧),然后总结y
对于给定的x
使用get.se(...)
误差线的函数。另一种选择是在使用 ggplot 之前汇总数据,然后使用geom_bar(...)
and geom_errorbar(...)
.
另外,绘制 +/- 1 se 并不是一个很好的做法(尽管它经常使用)。您最好绘制合法的置信限制,例如,您可以使用内置的mean_cl_normal
功能而不是做作get.se(...)
. mean_cl_normal
基于数据呈正态分布的假设返回 95% 置信限(或者您可以将 CL 设置为其他值;阅读文档 http://www.inside-r.org/packages/cran/ggplot2/docs/hmisc).