繁体   English   中英

将观察次数添加到多个 ggplot2 箱线图

[英]add number of observations to a multiple ggplot2 boxplots

我正在尝试使用描述性信息(平均值、计数等)创建箱线图。 我找到了很多关于如何为具有不同组的一个箱线图添加数字的示例,但我没有找到一种方法来为多个箱线图网格(facet_wrap)添加这些数字。

例如, 本文描述了如何为一个箱线图添加数字 - 我正在尝试为多个箱线图做同样的事情

library(reshape2)
library(ggplot2)
df.m <- melt(iris, id.var = "Species")
p <- ggplot(data = df.m, aes(x=variable, y=value)) + 
  geom_boxplot(aes(fill=Species))
p + facet_wrap( ~ variable, scales="free")

在此处输入图像描述

在此 plot 之上 - 我想在每个框的顶部添加相关的描述信息。

创建具有计数和意义的 function

stat_box_data <- function(y) {
  return( 
    data.frame(
      y = 0.5+1.1*max(y),  #may need to modify this depending on your data
      label = paste('count =', length(y), '\n',
                    'mean =', round(mean(y), 1), '\n')
    )
  )
}

  )
}
df.m <- melt(iris, id.var = "Species")

如果您有较大的异常值而不是上面的y=0.5...位,您可能想要使用这个或类似的东西:

y=quantile(y,probs=0.95)*1.1,

Plot 数据并将stat_summary与您的自定义 function 一起使用

ggplot(data = df.m, aes(x=Species, y=value)) + 
  geom_boxplot(aes(fill=Species))+
  stat_summary(
    fun.data = stat_box_data, 
    geom = "text", 
    hjust = 0.5,
    vjust = 0.9
  ) + 
facet_wrap( ~ variable, scales="free")

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM