【问题标题】:Add a number of observations per group AND SUBGROUP in ggplot2 boxplot在 ggplot2 boxplot 中为每组和子组添加多个观察值
【发布时间】:2016-04-22 07:53:42
【问题描述】:

这可能看起来像this question 的重复,但实际上我想扩展原始问题。

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

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)

我的问题是样本的数量都排在组的中心,而不是绘制在适当的箱线图上(如下图所示):

【问题讨论】:

  • 如果我理解正确,我认为你需要 facet_wrap。

标签: r ggplot2 boxplot


【解决方案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))

【讨论】:

  • 正是我需要的,谢谢!我可以发布后续问题吗?如果这是不好的做法,请要求删除此评论。否则:如果值相距甚远,使用一个因子来确定文本相对于组中位数的位置会导致不需要的行为。使用固定值(例如中位数(x)+5)使函数仅可用于一个值范围。有没有办法在 stat_summary() 命令中确定文本的 y 值?
  • 感谢您接受答案!对于您的评论,我不确定,但我个人更手动,但如果您想将标签准确地放在您想要的位置 geom_text() 可能是最好的选择
  • 替代方案:不是使用每个子组中位数的倍数,有没有办法访问整个数据集的中位数并使用该值的倍数?
  • 我认为这是可能的;看看这个docs.ggplot2.org/dev/geom_boxplot.html 并向下滚动,您将看到一个示例,您可以在其中使用自己的计算绘制箱线图
猜你喜欢
  • 2013-03-17
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
相关资源
最近更新 更多