如何在ggplot2中注释单个facet上的文本

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

这个问题是对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

有人有任何解释吗?

r ggplot2 facet-grid
1个回答
1
投票

发生了什么是一个因素问题。 首先,您将面对数据集cyl中的mtcars专栏。这是"numeric"类的一个对象,取三个不同的值。

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

然后,您创建一个新的数据集,即数据帧ann_text。但是你将cyl定义为类"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等级。 因此,当您组合两个数据集时,cyl有4个值,原始数字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")
© www.soinside.com 2019 - 2024. All rights reserved.