我正在尝试使用组合两个 ggplot 对象cowplot::plot_grid()
并垂直对齐它们。这通常非常简单,使用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")
然而,当 ggplots 使用时,这种方法会失败coord_equal()
因为plot_grid()
当强制纵横比时无法修改轴。相反,默认设置是保持每个图的高度相同。
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")
我可以通过玩并获得rel_heights
论点恰到好处,但这不是一个可行的解决方案,因为我有许多动态图要构建。这里,y 轴对齐,并且所有轴的坐标仍然相等。
cowplot::plot_grid(plot1, plot2, ncol = 1, align = "v", rel_heights = c(2, 1.07))
我见过很多解决类似问题的方法ggplot2::ggplotGrob()
and grid::grid_draw()
,但是当coord_equal()
用来。也许最好的解决方案不使用cowplot::plot_grid()
根本没有,或者解决方案可能是以某种方式动态确定并将正确的值传递给rel_heights
。我想我更喜欢后者,以便能够轻松使用附带的其他功能cowplot::plot_grid()
。也许可以找到一些有用的灵感这个相关的方法.