[英]add number of observations to a multiple ggplot2 boxplots
I'm trying to create boxplots with descriptive information (mean, count, etc.).我正在尝试使用描述性信息(平均值、计数等)创建箱线图。 I found a lot of examples of how to add the numbers for one boxplot with different groups, but I didn't found a way to add those numbers for multiple boxplots grid (facet_wrap).我找到了很多关于如何为具有不同组的一个箱线图添加数字的示例,但我没有找到一种方法来为多个箱线图网格(facet_wrap)添加这些数字。
for example, this article describes how to add numbers for one boxplot - I'm trying to do the same for multiple boxplots例如, 本文描述了如何为一个箱线图添加数字 - 我正在尝试为多个箱线图做同样的事情
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")
and on top of this plot - I want to add the relevant descriptive information on top of each box.在此 plot 之上 - 我想在每个框的顶部添加相关的描述信息。
Create the function that makes counts and means创建具有计数和意义的 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")
You may want to use this or something similar if you have large outliers instead of the y=0.5...
bit above:如果您有较大的异常值而不是上面的y=0.5...
位,您可能想要使用这个或类似的东西:
y=quantile(y,probs=0.95)*1.1,
Plot the data and use stat_summary
with your custom function 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.