ggplot2 boxplot stat_summary 按组放置文本

ggplot2 boxplot stat_summary text placement by group

在下图中,我希望在每个箱线图的顶部叠加观察的数量(在本例中为 40)。当有 fill 美学时,我的下面代码不起作用。文本需要水平调整(在本例中为 1 左、1 中、1 右),以便它们正确地覆盖相应的箱线图。

dt <- data.table(
    x = factor(rep(1:2, each=120))
    , f = rep(letters[1:3], 40)
    , y = c(rnorm(120, 1:3), rnorm(120, 1:3*2))
)
table(dt$x, dt$f)

+--------------+
|      a  b  c |
+--------------+
|   1 40 40 40 |
|   2 40 40 40 |
+--------------+

frequencyAnnotation <- function(x) {
   c(y = (quantile(x, .75, names = F) + median(x))/2, label=length(x))
}
ggplot(dt, aes(x=x, y=y, fill=f)) +
    geom_boxplot() +
    stat_summary(fun.data = frequencyAnnotation, geom='text')

当您使用参数 fill= 时,您的箱线图会被闪避,因此您必须将 position_dodge() 添加到 stat_summary() 调用中。

ggplot(dt, aes(x=x, y=y, fill=f)) +
      geom_boxplot() +
      stat_summary(fun.data = frequencyAnnotation, geom='text', 
                   position = position_dodge(width = 0.75))