R语言 在箱形图中添加每组的观察数

bxpogfeg  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(148)

以下问题:How to add a number of observations per group and use group mean in ggplot2 boxplot?,我也想在 ggplot boxplot中添加每组的观察数。但是我在 aes Map中添加了颜色。
现有答案显示了如何调整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

4nkexdtk

4nkexdtk1#

你可以使用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

6ojccjat

6ojccjat2#

可以使用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))

相关问题