如何绘制R中Boxplot的平均值和标准误差 [英] How to plot mean and standard error in Boxplot in R
问题描述
我有两个分类因子('Habitat'和'Locality')和一个连续变量(T)。 '人居'有两个层次,'地点'有八个层次。我想改变默认的胡须来表示SE,并且将中值转换为每个盒图的平均值。有没有办法做到这一点,并在绘图时考虑到两个分类因素?提前谢谢了。
这是我用boxplot ggplot的默认设置完成的,显示了具有中间间隔的第一和第三四分位数。
ggplot(data,aes(x = Locality,y = T))+
geom_boxplot(aes(fill =互动(Habitat,Locality),
group =互动(因子(Habitat),地点)),
outlier.shape = 1,outlier.size = 3)+
theme_bw()+
主题(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(color ='black'),
legend.position ='none',
axis.text.x = element_text(angle = 90,hjust = 1,size = 12))+
scale_y_continuous('T')+
xlab('Locality')
计算最小均值1SEM,平均值+平均值+ 1SEM和最大值的函数。然后使用 stat_summary
将这5个值映射到boxplot上。
library(gridExtra)
library(ggplot2)
MinMeanSEMMax< - function (x),平均(x)-sd(x)/ sqrt(长度(x)),平均值(x),平均值(x)+ sd(x)/ sqrt(length(x)),max(x))
名称(v)<-c(ymin,lower,middle,upper,ymax)
v
$ b $ g1 < - ggplot(mtcars,aes(因子(am),mpg))+ geom_boxplot()+
ggtitle(Regular Boxplot)
g2 < - ggplot(mtcars,aes(factor(am),mpg))+
stat_summary(fun.data = MinMeanSEMMax,geom =boxplot,color =red)+
ggtitle(Boxplot:Min,Mean-1SEM,Mean,Mean + 1SEM,Max)
grid.arrange(g1,g2,ncol = 2)
I have two categorical factors ('Habitat' and 'Locality'), and one continuous variable (T). 'Habitat' has two level and 'Locality' has eight levels. I want to change the default whiskers to represent the SE, and the median into the mean for each boxplot. Is there a way to do this and taking both of the categorical factors into account when plotting? Many thanks in advance.
This is what I have done with the default setting of boxplot ggplot, showing the first and third quartiles with median intervals.
ggplot(data,aes(x=Locality,y=T)) +
geom_boxplot(aes(fill=interaction(Habitat,Locality),
group=interaction(factor(Habitat),Locality)),
outlier.shape=1,outlier.size=3) +
theme_bw() +
theme(
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
axis.line=element_line(colour='black'),
legend.position='none',
axis.text.x=element_text(angle=90,hjust=1,size=12)) +
scale_y_continuous('T') +
xlab('Locality')
First write a function that compute the min, mean-1SEM, mean, mean+1SEM, and Max. Then map these 5 values onto a boxplot using stat_summary
.
library(gridExtra)
library(ggplot2)
MinMeanSEMMax <- function(x) {
v <- c(min(x), mean(x) - sd(x)/sqrt(length(x)), mean(x), mean(x) + sd(x)/sqrt(length(x)), max(x))
names(v) <- c("ymin", "lower", "middle", "upper", "ymax")
v
}
g1 <- ggplot(mtcars, aes(factor(am), mpg)) + geom_boxplot() +
ggtitle("Regular Boxplot")
g2 <- ggplot(mtcars, aes(factor(am), mpg)) +
stat_summary(fun.data=MinMeanSEMMax, geom="boxplot", colour="red") +
ggtitle("Boxplot: Min, Mean-1SEM, Mean, Mean+1SEM, Max")
grid.arrange(g1, g2, ncol=2)
这篇关于如何绘制R中Boxplot的平均值和标准误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!