r - ggplot注释grob位置不一致
问题描述
我正在尝试创建一系列在边距中包含注释的图形,这些图形应在图形中保持相同的绝对位置(这样如果按顺序查看多个图形,注释似乎不会移动)。
让 ggplot 允许在边距中进行注释而不扭曲图形本身是很复杂的,但我相信挑战已经解决(对于任何想知道的人,请参阅scales::squish
和clip = "off"
线)。现在,不幸的是,我的注释(文本 grobs)在图表之间并不一致。
在下面的代码中,我创建了两个简单的数据框(实际上是 tibbles),然后从它们创建基本的 ggplots。数据集之间的代码相同,只是自变量的级别数(x 轴上的刻度)在图表之间有所不同。据推测,x轴上的这种不一致是问题的根源,但我不知道如何解决。
library(ggplot2)
library(grid)
library(dplyr)
dat1 = data.frame(IV = c(rep("GroupA",50),rep("GroupB",50)),
DV = c(rnorm(n = 50, mean = 100, sd = 15),
rnorm(n = 50, mean = 115, sd = 15)))
dat2 = data.frame(IV = c(rep("GroupA",50),rep("GroupB",50),rep("GroupC",50),rep("GroupD",50)),
DV = c(rnorm(n = 50, mean = 100, sd = 15),
rnorm(n = 50, mean = 115, sd = 15),
rnorm(n = 50, mean = 85, sd = 15),
rnorm(n = 50, mean = 100, sd = 30)))
tibdat1 = as_tibble(dat1) %>%
group_by(IV) %>%
summarise(
M = mean(DV,na.rm=T))
tibdat2 = as_tibble(dat2) %>%
group_by(IV) %>%
summarise(
M = mean(DV,na.rm=T))
graph1 = ggplot(data = tibdat1, mapping = aes(IV, M)) +
geom_col() +
scale_y_continuous(breaks = c(1:150), limits = c(1,150), oob = scales::squish) +
coord_cartesian(clip = "off") +
annotation_custom(
grob = textGrob(label = "myGrob1", gp = gpar(col = "red", fontsize = 13), rot = 90), ymin = 50, ymax = 50, xmin = .2, xmax = .2)
graph2 = ggplot(data = tibdat2, mapping = aes(IV, M)) +
geom_col() +
scale_y_continuous(breaks = c(1:150), limits = c(1,150), oob = scales::squish) +
coord_cartesian(clip = "off") +
annotation_custom(
grob = textGrob(label = "myGrob2", gp = gpar(col = "blue", fontsize = 13), rot = 90), ymin = 50, ymax = 50, xmin = .2, xmax = .2)
请注意,graph1 的 myGrob1 和 graph2 的 myGrob2 在 x 轴上的位置略有不同——这就是问题所在。
解决方案
推荐阅读
- python - 我可以用二维数组的 numpy 数组提供深度学习模型吗?
- c++ - 通过回退到 C 的 C++ 类型双关语
- android - 为什么我在 Mac 上的 Android Studio 3.5.1 中出现 Gradle Sync 问题 Host is down
- php - PHP 是否不允许在变量初始化期间将数组类型转换为对象?
- c# - Microsoft DI 容器 _transientDisposables 未处理(内存泄漏)
- c# - 当前上下文中不存在名称“svar”
- c++ - 如何访问`std::variant`的任何孩子的`polymorphic`基类?
- java - 允许用户输入线程数并根据线程数分配添加到每个线程
- python - 我尝试了很多次从 booking.com 获取数据。但我做不到
- kotlin - 使用带有参数的辅助构造函数创建数据类实例,该参数是另一个类似的类