Likan Zhan
Likan Zhan

Reputation: 1076

`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 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"))

Upvotes: 2

Views: 1019

Answers (2)

Likan Zhan
Likan Zhan

Reputation: 1076

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 ~ .)

Upvotes: 1

Mal_a
Mal_a

Reputation: 3760

The problem is that You used for x= 2:3 and for y=20:21. X and Y should be given only one value/argument and not a vector as in Your case. If You change to x=2 and y=20, then the plot appears without any Error:

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

Upvotes: 0

Related Questions