【问题标题】:ggplot2 - annotate (labelling) geom_boxplot with position = dodgeggplot2 - 使用 position = dodge 注释(标记)geom_boxplot
【发布时间】:2014-04-27 23:24:38
【问题描述】:

当使用填充美学(或在 x 轴上躲避样本)时,我无法在箱线图附近添加标签(在这种情况下为样本大小)。

它适用于最常用的数据集(mtcars)和示例

library(ggplot2)

fun_length <- function(x){
  return(data.frame(y=median(x),label= paste0("n=", length(x))))
}

ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_boxplot() +
  stat_summary(aes(x = factor(cyl)),
               fun.data = fun_length, geom = "text",
               vjust = +1, size = 4)

library(plyr)
ddply(mtcars, .(cyl), summarise, label = length(mpg))

  cyl label
1   4    11
2   6     7
3   8    14

但我不能为这个版本添加相同的标签,现在显示每个 vs 级别的样本大小。

ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_boxplot(aes(fill = factor(vs))) +
  stat_summary(aes(x=factor(cyl)),
               fun.data = fun_length, geom = "text")

ddply(mtcars, .(cyl, vs), summarise, label = length(mpg))

  cyl vs label
1   4  0     1
2   4  1    10
3   6  0     3
4   6  1     4
5   8  0    14

欢迎任何帮助。提前致谢。

【问题讨论】:

    标签: r ggplot2 annotations label


    【解决方案1】:
    ggplot(mtcars, aes(factor(cyl), mpg)) +
      geom_boxplot(aes(fill = factor(vs)), position=position_dodge(.9)) +
      stat_summary(aes(x=factor(cyl), fill = factor(vs)), position=position_dodge(.9),
                   fun.data = fun_length, geom = "text",
                   vjust = +1, size = 4)
    

    【讨论】:

      【解决方案2】:

      这应该可行 - 将 vs 移动到 ggplot 调用,然后您就不需要在 stat_summary 中添加 aes 并添加 position_dodge(用于演示)

      ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(vs))) +
        geom_boxplot(position=position_dodge(width=0.9)) +
        stat_summary( fun.data = fun_length, geom = "text", 
                            position=position_dodge(width=0.9), vjust=2)
      

      【讨论】:

        猜你喜欢
        • 2012-06-15
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-03
        • 2012-07-21
        相关资源
        最近更新 更多