[英]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.