首页 > 解决方案 > 如何在ggplot2中的单个方面注释文本

问题描述

这个问题是后续问题:Annotating text on individual facet in ggplot2

我正在尝试接受的答案中提供的代码,并得到与提供的结果不同的东西。授予帖子较旧并且我使用的是 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)

https://github.com/RamenZzz/hello-world/blob/master/Rplot09b.jpeg?raw=true

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

这给了我正确的图表:

https://raw.githubusercontent.com/RamenZzz/hello-world/master/Rplot09a.jpeg

有人有什么解释吗?

标签: rggplot2facet-grid

解决方案


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

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

然后,您创建一个新数据集 dataframe 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,level"8"是级别编号3
因此,当您合并两个数据集时,有4 个cyl、原始数字46加上8数字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")

推荐阅读