如何在ggplot2的boxplot上添加mean和S.D或更改默认的whiskers定义来表示一个S.D.高于和低于数据的平均值?

时间:2014-08-29 14:16:39

标签: r ggplot2 boxplot

我有以下boxplot。三个网格用于三个不同的站点。三种颜色表示三种不同的方法。我想在每个箱图上添加均值和平均值+/- S.D.自定义箱图,其中胡须代表数据平均值之上和之下的一个标准偏差也是一种解决方案。我尝试了两种在互联网上找到但没有帮助的选项。

Three grids are are for three different sites. Three color denotes three methods. I want to add mean and mean+/-S.D on each boxplot.

示例R代码:

library(stats)  
library(ggplot2)
set.seed(50)
df <- data.frame(
site = rep(c("A", "B","C"),20),
# method=sample(c("method1", "method2","method3"), 60, replace = TRUE),
control = as.factor(c(rep(0,30),rep(1,30))),
x=1:60,
method1=rnorm(60),
method2=rnorm(60)+0.1,
method3=rnorm(60)+0.2

)  

m=melt(df,id.vars=c("control","site","x"))

p=ggplot(data=m, aes(control,y=value)) + 
geom_boxplot(aes(fill=variable))+ 
facet_grid(~site) 
print(p)

我尝试了两种选择:

选项1。

sd_upper=function(x) { mean(x)+sd(x) }
sd_lower=function(x) { mean(x)-sd(x) }

p=p+
stat_summary(fun.y=sd_upper, colour="yellow",geom="point", shape=95, size=5,show_guide = FALSE)+
stat_summary(fun.y=sd_lower, colour="yellow",geom="point", shape=95, size=5,show_guide = FALSE)+
stat_summary(fun.y=mean, colour="yellow",geom="point", shape=95, size=5,show_guide = FALSE)

enter image description here

这三个点仅绘制在中间箱图上。

选项2。

 min.mean.sd.max <- function(x) {
 r <- c(min(x), mean(x) - sd(x), mean(x), mean(x) + sd(x), max(x))
 names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
 r
 }

p=p+
stat_summary(fun.data = min.mean.sd.max,aes(fill=variable), geom = "boxplot") 

enter image description here

这不是我想要的!

有没有办法在ggplot2中更改geom_boxplot的默认定义,以便绘制平均值和S&gt; D?

0 个答案:

没有答案