1
votes

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:

Plot without geom_text

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

1
It works for me if you create ann_text a little differently: ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text", cyl = c(8), gear = c(4)). I was a bit confused by your choice of factor because gear and cyl are not factors in mtcars.CMichael
Thanks a lot, this indeed solved my problem!Ulrike

1 Answers

0
votes

@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)

enter image description here