首页 > 解决方案 > 组合并对齐ggplot,包括一个控制其高度的正方形

问题描述

我正在尝试垂直对齐几个ggplots,包括一个必须是正方形的(使用 coord_fixed 或任何其他方式)。我还希望能够控制不同地块的相对高度。所需的情节看起来像这样,矩形的数量:(想要的情节)。正方形下方的矩形地块的数量可以从 1 到 5 不等。

我已经阅读了其他 SO 线程,包括这个线程(使用 coord_equal() 时使用 cowplot::plot_grid() 垂直对齐不同高度的图)。

到目前为止:我可以对齐图,包括一个正方形(带有eggor patchwork)的图,但我无法调整面板的相对高度。以下是我尝试过的(使用cowplot,eggpatchwork包)。

使用 coord_fixed

#data
a = data.frame(x = seq(0,10), y = seq(10,20), z = runif(11))
b = data.frame(x = seq(0,10), y = runif(11))

#generate ggplot
library(ggplot2)
p1 = ggplot(a, aes(x = x, y = y, fill = z)) + geom_raster() + coord_fixed()
p2 = ggplot(b, aes(x = x, y = y)) + geom_line()


#align with cowplot => alignment not working if p1 is squared.
library(cowplot)
plot_grid(p1,p2,p2, ncol = 1, align = 'v', axis = 'lr')

#align with patchwork => working with p1 squared, but can't control the relative heights
library(patchwork)
p1 + p2 + p2 + plot_layout(nrow = 3)              #aligned, p1 being square
p1 + p2 + p2 + plot_layout(nrow = 3, 
                           heights = c(3, 1, 1))  #not aligned

#same, it does not seem to work with egg.
library(egg)
egg::ggarrange(p1, p2, p2, ncol = 1) 
egg::ggarrange(p1, p2, p2, ncol = 1, heights = c(3,1,1))

--

另一种策略是不对 p1 使用 coord_fixed,使用导出文件尺寸并以“正确”尺寸导出

p1bis = ggplot(a, aes(x = x, y = y, fill = z)) + geom_raster()
plot_grid(p1bis,p2,p2, ncol = 1, align = 'v', axis = 'lr', rel_heights = c(4,1,1))
ggsave("temp.pdf", width = 18, height = 24.5, units = "cm")

但是我不清楚如何以动态方式计算导出PDF文档的宽高比。有没有办法提取(以 npc 为单位?)panel.border 的宽度和高度?

--

我还遇到了这个ggh4x包,它和 egg 一样,包含一个设置面板大小的函数。但是与拼凑组合时,面板尺寸信息似乎丢失了

library(ggh4x)
p1f = p1bis + force_panelsizes(rows = unit(10, "cm"), cols = unit(10, "cm"))
p2f = p2    + force_panelsizes(cols = unit(10, "cm"), rows = unit(3, "cm"))
p1f + p2f + p2f + plot_layout(nrow = 3)

你还有其他建议吗?我在某处遗漏了一些微不足道的东西吗?

谢谢你的时间 !

标签: rggplot2eggcowplotpatchwork

解决方案


{patchwork}网站上描述了固定方面图的情况:

组装图的一个特殊情况是处理固定纵横比图,例如使用 coord_fixed()、coord_polar() 和 coord_sf() 创建的图。不可能同时分配偶数尺寸和对齐固定纵横图。

...

需要哪种解决方案可能取决于具体的用例。

在您的情况下,一种方法是嵌套图:

library(ggplot2)
library(patchwork)

p22 <- p2 + p2 + plot_layout(nrow = 2)      
p1 + p22 + plot_layout(nrow = 2)

reprex 包于 2021-05-11 创建(v0.3.0)

这没有对高度进行微调控制,但我们可以使用plot_spacer()s 调整嵌套图:

library(patchwork)

p22 <- plot_spacer() + p2 + plot_spacer() + p2 + plot_spacer() + plot_layout(heights = c(1, 2, 1, 2, 1))      

p1 + p22 + plot_layout(nrow = 2)

reprex 包于 2021-05-11 创建(v0.3.0)


推荐阅读