1

I have a ggplot facet_grid where I want to add different text labels to each individual plot.

enter image description here

I have read this for mapping to a one-dimensional facet_grid

library(ggplot2)

ann_text <- data.frame(mpg = c(14,15),wt = c(4,5),lab=c("text1","text2"),
                       cyl = factor(c(6,8),levels = c("4","6","8")))

p <- ggplot(mtcars, aes(mpg, wt)) + 
  geom_point() + 
  facet_grid(gear ~ cyl) +
  geom_text(data = ann_text,aes(label =lab) )

But this produces the following: enter image description here

How does the matching to ann_text work inside the geom_text?

pluke
  • 3,832
  • 5
  • 45
  • 68

1 Answers1

2

You need to specify both cyl and gear in your ann_text data.frame, as these are the variables you are using for facetting:

library(ggplot2)

ann_text <- data.frame(mpg = c(14,15),
                       wt = c(4,5),
                       lab=c("text1","text2"),
                       cyl = c(6,8),
                       gear = 3)

ggplot(mtcars, aes(mpg, wt)) + 
  geom_point() + 
  facet_grid(gear ~ cyl) +
  geom_text(data = ann_text, aes(label = lab))

enter image description here

From there, it's pretty easy to get what you're looking for:

ann_text2 <- data.frame(mpg = 14,
                       wt = 4,
                       lab = paste0('text', 1:9),
                       cyl = rep(c(4, 6, 8), 3),
                       gear = rep(c(3:5), each = 3))

ggplot(mtcars, aes(mpg, wt)) + 
  geom_point() + 
  facet_grid(gear ~ cyl) +
  geom_text(data = ann_text2, aes(label = lab))

enter image description here

bouncyball
  • 10,631
  • 19
  • 31
  • thanks, of note is that the x and y values from the ggplot(aes()) command, i.e. mpg and wt, MUST be present in the ann_text2 data_frame. This stumped me – pluke Jan 18 '18 at 12:12