在 ggplot2 boxplot 中添加每组的观察数 [英] Add number of observations per group in ggplot2 boxplot

查看:31
本文介绍了在 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

这篇关于在 ggplot2 boxplot 中添加每组的观察数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆