I want to add two annotations to the ggplot graph.
When the graph doesn't contain a facet_grid
, such as p1
, adding such a annotate
layer works fine, i.e., q1
. However, when I add a facet_grid
layer, to the original graph, i.e., p2
, then adding the same 'annotate' layer, i.e., q2
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"))
The following is the answer I got from the package author, Hadley Wickham:
https://github.com/tidyverse/ggplot2/issues/2221
Unfortunately it's very hard to have annotate()
do this automatically. Instead just do it "by hand" by creating the dataset yourself.
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 ~ .)