如何在 ggplot2 中的单个方面注释文本

How to annotate text on individual facet in ggplot2

此问题是以下问题的后续问题:Annotating text on individual facet in ggplot2

我正在尝试接受的答案中提供的代码,但得到的结果与提供的结果出奇地不同。授予 post 较旧并且我使用的是 R 3.5.3 和 ggplot2 3.1.0,但我得到的似乎没有意义。

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

#below is how the original post created a dataframe for the text annotation
#this will produce an extra facet in the plot for reasons I don't know
ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text",cyl = factor(8,levels = c("4","6","8")))

p+geom_text(data = ann_text,label = "Text")

这是链接问题中已接受答案的代码。对我来说,它生成了以下带有额外方面的图表(即,似乎已将 3 的附加分类变量添加到 cyl)

#below is an alternative version that produces the correct plot, that is,
#without any extra facets.
ann_text_alternate <- data.frame(mpg = 15,wt = 5,lab = "Text",cyl = 8)

p+geom_text(data = ann_text_alternate,label = "Text")

这给了我正确的图表:

有人解释一下吗?

这是一个因素问题。
首先,您按数据集 mtcars 中的一列 cyl 分面。这是一个 class "numeric" 的对象,具有 3 个不同的值。

unique(mtcars$cyl)
#[1] 6 4 8

然后,您创建一个新的数据集,即数据框 ann_text。但是你把cyl定义为class"factor"的对象。而这个专栏里的内容可以用 str.

查看
str(ann_text)
#'data.frame':  1 obs. of  4 variables:
# $ mpg: num 15
# $ wt : num 5
# $ lab: Factor w/ 1 level "Text": 1
# $ cyl: Factor w/ 3 levels "4","6","8": 3

R 将因子编码为从 1 开始的整数,级别 "8" 是级别编号 3
因此,当您合并两个数据集时,cyl4 个值,原始数字 468 加上新 数量 3。因此,额外的方面。

这也是该解决方案有效的原因,在数据框中 ann_text_alternatecyl 是一个采用现有值之一的数字变量。

另一种让它起作用的方法是在分面时强制 cyl 考虑因素。注意

levels(factor(mtcars$cyl))
#[1] "4" "6" "8"

并且新数据框 ann_text 不再有第 4 层。开始按照问题绘制图表

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

并添加文本。

p + geom_text(data = ann_text, label = "Text")