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

时间:2015-03-04 03:48:03

标签: r ggplot2

关注这个问题: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

enter image description here

感谢您的任何建议。

2 个答案:

答案 0 :(得分:10)

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

enter image description here

width的{​​{1}}参数控制水平轴上的定位。 0.75是最佳点,看看它如何适用于不同数量的分组:

position_dodge()

enter image description here

答案 1 :(得分:3)

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