在ggplot2 boxplot中为每组AND SUBGROUP添加一些观察结果

时间:2016-01-16 22:21:11

标签: r ggplot2 boxplot

这似乎与this question重复,但实际上我想扩展原始问题。

我想用ggplot中每组和SUBGROUP的观察数来表示箱线图。按照示例或原始帖子,这是我的最小例子:

require(ggplot2)

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

ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(gear))) +
  geom_boxplot() +
  stat_summary(fun.data = give.n, geom = "text", fun.y = median)

我的问题是样本数量全部排在组的中心,而不是在适当的箱线图上绘制(如下图所示):Annotes are centering in the middle of the group rather than plotting on the appropriate boxplot

1 个答案:

答案 0 :(得分:1)

是你想要的吗?

require(ggplot2)

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

ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(gear))) +
  geom_boxplot() +
  stat_summary(fun.data = give.n, geom = "text", fun.y = median, position=position_dodge(width=0.75))

enter image description here