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

Add number of observations per group in ggplot2 boxplot

根据这个问题:How to add a number of observations per group and use group mean in ggplot2 boxplot?,我也想在 ggplot boxplot 中添加每组的观察数。但是我在 aes 映射中添加了一种颜色。

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

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

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 是最佳点,看看它如何适用于不同数量的分组:

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

您可以使用 geom_text 而不是 stat_summary。请参考以下问题:ggplot2 add text on top of boxplots.

这是一个关于如何使用观察次数的示例:

# Create an aggregate of median & count
> cts <- merge(aggregate(mpg ~ cyl + am, mtcars, length), 
               aggregate(mpg ~ cyl + am, mtcars, median), 
               by=c("cyl", "am"))
# Rename the col names to fit with the original dataset..
> names(cts) <- c("cyl", "am", "count", "mpg")
# As alexwhan suggested, position_dodge helps with positioning
# along the x-axis..
> ggplot(mtcars, aes(factor(cyl), mpg, colour = factor(am))) + 
  geom_boxplot(position = position_dodge(width=1.0)) + 
  geom_text(data = cts, aes(label=count), 
            position=position_dodge(width=1.0))