How to plot mean and standard error in Boxplot in R

时间秒杀一切 提交于 2019-11-30 15:29:38

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)

I expect that it is possible, but it is also possible to put up a traffic sign that is a red octagon and says "Increased speed limit ahead", I expect that both will be more confusing that helpful. The boxplot has a standard definition of what the parts represent. When a user sees a boxplot they should not have to go through extra mental gymnastics to rethink what the different parts mean. Why not use a different representation if you don't want to represent these standard summaries. The geom_crossbar or geom_errorbar function/geoms may be more appropriate for your display (and probably easier to use than trying to modify the boxplot geom).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!