在position_dodge()之后在ggplot2中添加注释?

时间:2019-06-10 10:42:59

标签: r ggplot2 annotate

我正在尝试在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"))

我真正想做的是同时注释每个级别的“上午”。

这是我天真的尝试:

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和标签的数量。我怀疑答案在于为注释分配“上午”级别,但是我不知道该怎么做。有人有可行的解决方案吗?

2 个答案:

答案 0 :(得分: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")))

enter image description here

答案 1 :(得分:1)

代替硬编码标签位置,而是预先计算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))

enter image description here