【问题标题】:Annotate in ggplot2 following position_dodge()?在 position_dodge() 之后在 ggplot2 中进行注释?
【发布时间】:2019-06-10 10:42:59
【问题描述】:

我正在尝试在 R 中生成一个双因子实验的图形。这包含三个级别,每个级别都有两个子级别。我想对这些组中的每一个进行注释,但找不到合理的方法。

这是一个为顶层生成注释的示例:

ggplot(mtcars, aes(x = as.factor(cyl), y = mpg)) +
  geom_point(aes(colour = as.factor(am)), position = position_dodge(0.5)) +
  annotate("text", x = 1:3, y = c(37, 25, 22),
           label = c("a", "b", "c"))

我真正想做的是注释“am”的每个级别。

这是我的天真尝试:

ggplot(mtcars, aes(x = as.factor(cyl), y = mpg)) +
  geom_point(aes(colour = as.factor(am)), position = position_dodge(0.5)) +
  annotate("text", x = 1:6, y = c(27, 37, 25, 25, 22, 17),
           label = c("a", "b", "c", "d", "e", "f"), position = position_dodge(0.5))

> Error: Unequal parameter lengths: x (6), y (6), label (6), position (3)

我尝试改变 x、y 和标签的数量。我怀疑答案在于为注释分配“am”级别,但我不知道该怎么做。谁有可行的解决方案?

【问题讨论】:

    标签: r ggplot2 annotate


    【解决方案1】:

    也许改用geom_text

    library(ggplot2)
    
    ggplot(mtcars, aes(x = cyl, y = mpg)) +
      geom_point(aes(colour = as.factor(am)), position = position_dodge(0.5)) +
      geom_text(data = data.frame(x = c(3.8, 4.2, 5.8, 6.2, 7.8, 8.2), 
                                  y = c(27, 37, 25, 25, 22, 17)), 
      aes(x, y, label = c("a", "b", "c", "d", "e", "f")))
    

    【讨论】:

      【解决方案2】:

      预先计算 y 值,而不是硬编码标签位置,并使用 aesgroup 映射 x 位置。

      # calculate desired y positions for cyl * am combinations, e.g. max 
      d <- aggregate(mpg ~ am cyl, data = mtcars, max)
      
      # some toy labels
      d$lab <- letters[1:nrow(d)]
      
      # calculate desired y positions for cyl groups, e.g. mean of am max
      d2 <- aggregate(mpg ~ cyl, data = d, mean)
      
      # some toy labels
      d2$lab <-LETTERS[1:nrow(d2)]
      
      pd <- position_dodge(width = 0.5)
      
      ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
        geom_point(aes(colour = factor(am)), position = pd) + 
        geom_text(data = d, aes(y = mpg + 1, label = lab, group = factor(am)), position = pd) +
        geom_text(data = d2, aes(label = lab))
      

      【讨论】:

      • 嗨@R。拉莫!只是好奇:我的回答是否如您所愿?如果需要进一步的调整,请告诉我。干杯。
      猜你喜欢
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 2015-05-20
      • 1970-01-01
      相关资源
      最近更新 更多