Likan Zhan Likan Zhan - 1 year ago 102
R Question

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

I want to add two annotations to the ggplot graph.
When the graph doesn't contain a

, such as
, adding such a
layer works fine, i.e.,
. However, when I add a
layer, to the original graph, i.e.,
, then adding the same 'annotate' layer, i.e.,
results in an error reporting:

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

Any suggestion? Thanks.

PS, the version of the package ggplot2 I used is 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"))

Answer Source

The following is the answer I got from the package author, Hadley Wickham:

Unfortunately it's very hard to have annotate() do this automatically. Instead just do it "by hand" by creating the dataset yourself.

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 ~ .)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download