Description
As discussed here: #3303 (comment)
Annotations break when there are multiple facets and a non-position aesthetic/parameter is provided as a vector:
library(ggplot2)
data <- data.frame(x = c(1, 2), y = c(1, 2), facet = c("a", "b"))
p <- ggplot(data, aes(x, y)) + geom_point() + facet_grid(vars(facet))
p + annotate("text", x = 1.5, y = 1.5, label = c("label1", "label2"))
#> Error: Aesthetics must be either length 1 or the same as the data (4): label
Created on 2019-05-06 by the reprex package (v0.2.1)
I note that this problem does not occur when a position aesthetic is provided as a vector:
library(ggplot2)
data <- data.frame(x = c(1, 2), y = c(1, 2), facet = c("a", "b"))
p <- ggplot(data, aes(x, y)) + geom_point() + facet_grid(vars(facet))
p + annotate("text", x = c(1, 2), y = 1.5, label = "label")
Created on 2019-05-06 by the reprex package (v0.2.1)
As an additional hint to what may be happening, I note that the data frame that is internally being generated is twice as long as the input vector, as we can tell from the error message:
...same as the data (4)...
If we try to provide a longer label vector, we get an even longer data frame:
library(ggplot2)
data <- data.frame(x = c(1, 2), y = c(1, 2), facet = c("a", "b"))
p <- ggplot(data, aes(x, y)) + geom_point() + facet_grid(vars(facet))
p + annotate("text", x = 1.5, y = 1.5, label = c("label1", "label2", "label3", "label4"))
#> Error: Aesthetics must be either length 1 or the same as the data (8): label
Created on 2019-05-06 by the reprex package (v0.2.1)
I don't immediately know what the correct behavior here should be. Since we're not in any way specifying facets in the annotation, how should ggplot2 know that one label should be placed onto each facet, rather than both labels on each facet?