将geom_text添加到2D facet_grid ggplot

时间:2018-01-17 13:42:34

标签: r ggplot2

我有一个ggplot facet_grid,我想为每个单独的图添加不同的文本标签。

enter image description here

我已阅读this以映射到一维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) )

但这会产生以下结果: enter image description here

ann_text的匹配如何在geom_text内工作?

1 个答案:

答案 0 :(得分:2)

您需要在cyl gear中同时指定ann_text data.frame,因为这些是您用于分面的变量:

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

从那里,很容易得到你正在寻找的东西:

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

相关问题