r - 使用 coord_equal() 时使用 cowplot::plot_grid() 垂直对齐不同高度的图

标签 r ggplot2 gtable cowplot

我正在尝试使用 cowplot::plot_grid() 组合两个 ggplot 对象并垂直对齐它们。这通常使用 align = "v" 非常简单。

dat1 <- data.frame(x = rep(1:10, 2), y = 1:20)
dat2 <- data.frame(x = 1:10, y = 1:10)
plot1 <- ggplot(dat1, aes(x = x, y = y)) + geom_point()
plot2 <- ggplot(dat2, aes(x = x, y = y)) + geom_point()
cowplot::plot_grid(plot1, plot2, ncol = 1, align = "v")

image 1

但是,当 ggplots 使用 coord_equal() 时,这种方法会失败,因为当强制纵横比时,plot_grid() 无法修改轴。相反,默认设置是保持每个地 block 的高度相同。

plot1 <- ggplot(dat1, aes(x = x, y = y)) + geom_point() + coord_equal()
plot2 <- ggplot(dat2, aes(x = x, y = y)) + geom_point() + coord_equal()
cowplot::plot_grid(plot1, plot2, ncol = 1, align = "v")

image 2

我可以通过玩弄并获得恰到好处的 rel_heights 参数来强制实现我的目标,但这不是一个可行的解决方案,因为我要构建许多动态图。在这里,y轴是对齐的,所有轴的坐标仍然相等。

cowplot::plot_grid(plot1, plot2, ncol = 1, align = "v", rel_heights = c(2, 1.07))

image 3

我见过许多利用 ggplot2::ggplotGrob()grid::grid_draw() 解决类似问题的方法,但是当coord_equal() 被使用。也许最好的解决方案根本不使用 cowplot::plot_grid(),或者解决方案可能以某种方式动态确定正确的值并将其传递给 rel_heights。我想我更喜欢后面的选项,以便能够轻松使用 cowplot::plot_grid() 附带的其他功能。或许可以在 this related approach 中找到一些有用的灵感.

最佳答案

cowplot::plot_grid() 的作者在这里。当您尝试使用 coord_equal() 生成的指定纵横比对齐图时,它不起作用。解决方案是使用 egg 库或 patchwork 库。 Patchwork 仍在开发中,但应该很快就会发布到 CRAN。同时,您可以从 github 安装。

这是一个使用 egg 的解决方案。在我看来,它工作得很好。

library(ggplot2)
library(egg)

dat1 <- data.frame(x = rep(1:10, 2), y = 1:20)
dat2 <- data.frame(x = 1:10, y = 1:10)
plot1 <- ggplot(dat1, aes(x = x, y = y)) + geom_point() + coord_equal()
plot2 <- ggplot(dat2, aes(x = x, y = y)) + geom_point() + coord_equal()
ggarrange(plot1, plot2, ncol = 1)

enter image description here

我看到的两个小问题是 (1) 两个 y 轴的轴刻度不同,这使得间距看起来不同,以及 (2) 轴扩展到不同的限制。您可以通过手动设置刻度和扩展来解决这两个问题。

plot1 <- ggplot(dat1, aes(x = x, y = y)) + geom_point() + 
  scale_y_continuous(limits = c(0, 21), breaks = 5*(0:4), expand = c(0, 0)) +
  coord_equal()
plot2 <- ggplot(dat2, aes(x = x, y = y)) + geom_point() + 
  scale_y_continuous(limits = c(0, 11), breaks = 5*(0:4), expand = c(0, 0)) +
  coord_equal()
ggarrange(plot1, plot2, ncol = 1)

enter image description here

关于r - 使用 coord_equal() 时使用 cowplot::plot_grid() 垂直对齐不同高度的图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48924219/

相关文章:

r - 使用 ggplot2 通过函数传递绘图标签

r - 图标题学名+textGrob gtable中的符号

r - 使用 grid_draw 方法而不是 gridExtra 保存绘图

r - 在目录中加载新文件

r - 使用 ggplot2 更改时间序列上的 x 滴答数

正则表达式删除 r 中的 .csv

r - 我的分组横杆不躲避,而我的箱形图却躲避

r - 尝试使用 ggplot2 中的 facet_wrap 修复条宽时重叠条

r - 如何管理 gtable() 的 t、b、l、r 坐标以正确绘制次要 y 轴的标签和刻度线

对角线上具有非零值的 R 距离矩阵 (rdist.earth )