简体   繁体   中英

adding geom_text to 2D facet_grid ggplot

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

在此处输入图片说明

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: 在此处输入图片说明

How does the matching to ann_text work inside the geom_text ?

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

在此处输入图片说明

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM