This is a follow-up question on the post Annotating text on individual facet in ggplot2 which already helped me a lot, but it considers facets with a single variable.
I would like to add text to a single panel of a ggplot graph with 2 faceting variables (facet_grid).
The code before adding text:
p <- ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
facet_grid(gear ~ cyl)
results in the following plot:
When I add geom_text, the annotation is added correctly, but 2 additional and meaningless panels without data are added:
ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text",
cyl = factor(8,levels = c("4","6","8")), gear = factor(4, levels = c("3", "4", "5")))
p + geom_text(data = ann_text,label = "Text")
Plot with geom_text, mind 2 additional panels without data
How can I get rid of these 2 additional panels without data?
Thanks a lot for your time
@ulrike how about we treat gear
and cyl
as factors in the facet_grid()
call? This way you'll not have to change the data at all. The reason I'm treating gear
and cyl
as factors because, if you look at the structure of mtcars
dataset, you will notice gear
and cyl
contain discrete values. This means we can coerce them to factor
.
library(ggplot2)
ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text",
cyl = factor(8,levels = c("4","6","8")),
gear = factor(4, levels = c("3", "4", "5")))
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
facet_grid(factor(gear) ~ factor(cyl))+
geom_text(aes(mpg,wt, label=lab),
data = ann_text)