将geom_text添加到2D facet_grid ggplot

问题描述 投票:1回答:1

我有一个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内部发挥作用?

r ggplot2
1个回答
2
投票

你需要在你的cyl gear中指定ann_textdata.frame,因为这些是你用于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

从那里,很容易得到你想要的东西:

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

© www.soinside.com 2019 - 2024. All rights reserved.