在 ggplot2 boxplot 中添加每组的观察数

问题描述:

按照这个问题:如何在 ggplot2 boxplot 中为每组添加多个观察值并使用组均值?,我想也在 ggplot boxplot 中添加每组的观察数.但是我在 aes 映射中添加了一种颜色.

Following this question: How to add a number of observations per group and use group mean in ggplot2 boxplot?, I want to add number of observations per group in ggplot boxplot too. But I have added a colour into aes mapping.

现有答案显示了如何在 y 轴上调整文本位置.如何调整 x 轴上的文本位置?

The existing answer shows how to adjust text position in y axis. How could I adjust the text position in the x axis?

这是重现我的问题的最小示例:

This is a minimum example to reproduce my problem:

library(ggplot2)

give.n <- function(x){
  return(c(y = median(x)*1.05, label = length(x))) 
  # experiment with the multiplier to find the perfect position
}


p <- ggplot(mtcars, aes(factor(vs), mpg, colour = factor(am))) + 
    geom_boxplot() +
    stat_summary(fun.data = give.n, geom = "text", fun.y = median)
p

感谢您的任何建议.

你可以直接使用position:

p <- ggplot(mtcars, aes(factor(vs), mpg, colour = factor(am))) +  
     geom_boxplot() +
     stat_summary(fun.data = give.n, geom = "text", fun.y = median,
                  position = position_dodge(width = 0.75))
p

position_dodge()width 参数控制水平轴上的定位.0.75 是最佳点,看看它如何适用于不同数量的分组:

The width argument of position_dodge() controls the positioning on the horizontal axis. 0.75 is the sweet spot, see how it works for different numbers of groupings:

p2 <- ggplot(mtcars, aes(factor(vs), mpg, colour = factor(cyl))) + 
      geom_boxplot() +
      stat_summary(fun.data = give.n, geom = "text", fun.y = median, 
                   position = position_dodge(width = 0.75))
p2