`ggplot2` 中的 `annotate` 在与 `facet_grid` 结合时报告错误

`annotate` in `ggplot2` reports errors when combined with `facet_grid`

我想给 ggplot 图添加两个注释。 当图形不包含 facet_grid,例如 p1 时,添加这样的 annotate 层效果很好,即 q1。但是,当我向原始图形添加 facet_grid 层时,即 p2,然后添加相同的 'annotate' 层,即 q2 会导致错误报告:

Error: Aesthetics must be either length 1 or the same as the data (4): label

有什么建议吗?谢谢。

PS,我用的ggplot2包的版本是2.2.1.

p1 <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() p2 <- p1 + facet_grid(vs~.) q1 <- p1 + annotate("text", x = 2:3, y = 20:21, label = c("my label", "label 2")) q2 <- p2 + annotate("text", x = 2:3, y = 20:21, label = c("my label", "label 2"))

问题是您使用了 x= 2:3y=20:21。 X 和 Y 应该只给出一个 value/argument 而不是像你的情况那样的向量。如果您更改为 x=2y=20,则显示该图时没有任何错误:

ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + facet_grid(vs~.) + annotate("text", x = 2, y = 20, label = c("my label", "label 2"))

以下是我从软件包作者 Hadley Wickham 那里得到的答案:

https://github.com/tidyverse/ggplot2/issues/2221

不幸的是,很难让 annotate() 自动执行此操作。相反,只需 "by hand" 自己创建数据集即可。

library(ggplot2)
df <- data.frame(wt = 2:3, mpg = 20:21, label = c("my label", "label 2"))
ggplot(mtcars, aes(wt, mpg)) + 
geom_point() +
geom_text(aes(label = label), data = df) + 
facet_grid(vs ~ .)