ggplot2 # 2 中单个方面的注释文本

Annotation text on individual facet in ggplot2 # 2

这是 post Annotating text on individual facet in ggplot2 的后续问题,它已经帮了我很多,但它考虑的是具有单个变量的方面。

我想将文本添加到具有 2 个分面变量 (facet_grid) 的 ggplot 图的单个面板中。

添加文字前的代码:

p <- ggplot(mtcars, aes(mpg, wt)) + 
geom_point() +
facet_grid(gear ~ cyl)

结果如下图:

Plot without geom_text

当我添加 geom_text 时,注释添加正确,但添加了 2 个额外且无意义的没有数据的面板:

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

如何去掉这 2 个没有数据的附加面板?

非常感谢您的宝贵时间

@ulrike 我们如何将 gearcyl 视为 facet_grid() 调用中的因素?这样,您根本不必更改数据。我将 gearcyl 视为因素的原因是,如果您查看 mtcars 数据集的结构,您会注意到 gearcyl 包含离散值。这意味着我们可以强制他们 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)