r - 如何使用 ggplotGrob 和 annotation_custom 将 grob 与 ggplot 对齐?
问题描述
我正在使用 ggplot 创建一个 grob ggplotGrob
,然后将其添加为复杂的 ggplot 构造中的背景层,因为在具有大型数据集annotation_custom
的绘图中性能得到了很大改善。facet_wrap
但是我无法将底层 grob 与 ggplot 正确对齐。
这个简单的示例显示了我要解决的问题。
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
geom_point(color = "red")
ggplot(mtcars, aes(wt, mpg)) +
annotation_custom(grob = ggplotGrob(p)) +
geom_point()
我希望带有红点的情节完全位于带有黑点的情节下方。
解决方案
在将其添加为自定义注释之前,您可能只想抓取没有轴、边距等的面板。在下面的示例中,我将红点放大,以便您可以看到它们重叠。
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
geom_point(color = "red", size = 3)
grab_panel <- function(p) {
gt <- ggplotGrob(p)
layout <- gt$layout
is_panel <- which(layout$name == "panel")[[1]]
i <- layout$t[is_panel]
j <- layout$l[is_panel]
gt[i,j]
}
ggplot(mtcars, aes(wt, mpg)) +
annotation_custom(grob = grab_panel(p)) +
geom_point()
由reprex 包于 2021-03-20 创建(v1.0.0)
推荐阅读
- react-native - 由于任务':app:compileReleaseJavaWithJavac'的执行失败,无法制作Azure持续集成构建管道
- performance - 大型 CSV 文件中的高效搜索模式
- java - 无法在 intellij 中导入 Eclipse 项目
- python - 仅当 slug 存在冲突时才添加标识符
- sql - 无法从 makefile 连接到 PostgreSQL 并运行迁移脚本
- python - 在 Python 中根据某些条件删除所有行
- amazon-web-services - AWS EKS 没有暴露的端口
- python-3.x - 使用 plt.scatter 绘制聚集的 np.array
- python - mpld3 图中的绝对位置
- java - 添加空数组作为查询参数