r - 如何在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)
#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")
这给了我正确的图表:
有人有什么解释吗?
解决方案
发生了什么是一个因素问题。
首先,您按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
、原始数字4
和6
加上8
新数字、3
。因此,额外的方面。
这也是解决方案有效的原因,在数据框ann_text_alternate
列cyl
中是一个数值变量,采用现有值之一。
另一种使它起作用的方法是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")
推荐阅读
- javascript - 计算对象属性给出的结果与点表示法不同
- python - matplotlib 和后端“agg”导致绘图未显示
- string - 删除elisp中的括号
- light - Unity Issue Shadow Caster 2D
- c - 以不同方式处理最后一个参数的可变参数宏
- android - 带有选项卡布局的视图寻呼机超出屏幕范围
- node.js - Node.js 中的 Firebase Admin SDK 全局应用初始化
- python - 如何在熊猫中将浮点值转换为 date9 格式
- openflow - Openflow Floodlight:如何强制服务器在特定界面上运行?
- excel - 尝试从 XLA 文件中的 XLSX 电子表格获取信息