【发布时间】:2020-10-07 13:26:05
【问题描述】:
我希望将观察数添加到此箱线图中,不是按组,而是按因子分隔。另外,我希望显示除了看起来像这样的 x 轴标签之外的观察数:(“PF(N = 12)”)。 此外,我想显示盒子内每个盒子的平均值,以百万显示,以免每个盒子都有一个巨大的数字。
这是我得到的:
give.n <- function(x){
return(c(y = median(x)*1.05, label = length(x)))
}
mean.n <- function(x){x <- x/1000000
return(c(y = median(x)*0.97, label = round(mean(x),2)))
}
ggplot(Soils_noctrl) +
geom_boxplot(aes(x=Slope,y=Events.g_Bacteria, fill = Detergent),
varwidth = TRUE) +
stat_summary(aes(x = Slope, y = Events.g_Bacteria), fun.data = give.n, geom = "text",
fun = median,
position = position_dodge(width = 0.75))+
ggtitle("Cell Abundance")+
stat_summary(aes(x = Slope, y = Events.g_Bacteria),
fun.data = mean.n, geom = "text", fun = mean, colour = "red")+
facet_wrap(~ Location, scale = "free_x")+
scale_y_continuous(name = "Cell Counts per Gram (Millions)",
breaks = round (seq(min(0),
max(100000000), by = 5000000),1),
labels = function(y) y / 1000000)+
xlab("Sample")
到目前为止,它看起来像这样: As you can see, the mean value is at the bottom of the plot and the number of observations are in the boxes but not separated
感谢您的帮助!干杯
【问题讨论】:
-
没有任何样本数据很难做出好的推荐。见stackoverflow.com/a/5965451/4114240。我最好的猜测是您的问题是 stat_summary 没有继承 aes,而是定义了一个新的并且不包括 Detergent。因此,如果没有根据 Detergent 因子将它们分开,代码会将文本放在箱线图所在的位置。只是我最好的猜测。 HTH
-
使用 geom_text 作为样本大小和平均值可能更容易 - 您可以设置 x 和 y 坐标,例如geom_text(aes(x = Slope, y = min(Events.g.bacteria), label = give.n)) + geom_text(aes(x = Slope, y = 1.1 * min(Events.g.bacteria), label = mean.n)) 应将样本编号放在底部,将平均值放在其上方。您可能需要稍微调整一下比例(例如 0.9*min(...) 等)
-
另一个可能的想法是
fill参数在 facet 和 x 变量的组合之间拆分数据。但是中值和均值函数使用给定组合中的所有值。特别是,有多少行数据适合AL_S和Buot方面?有 9 个吗?