问题描述
我正在尝试垂直对齐多个 ggplots
,包括一个必须是方形的(使用 coord_fixed 或任何其他方式)。我还希望能够控制不同地块的相对高度。所需的情节看起来像这样,矩形的数量:(wanted plot)。正方形下方的矩形图的数量可以从 1 到 5 不等。
我已经阅读了其他 SO 主题,包括这个 (Vertically align of plots of different heights using cowplot::plot_grid() when using coord_equal())。
到目前为止:我可以对齐地块,包括方形地块(使用 egg
或 patchwork
),但我无法调整面板的相对高度。
以下是我尝试过的(使用 cowplot
、egg
或 patchwork
包)。
使用 coord_fixed
#data
a = data.frame(x = seq(0,10),y = seq(10,20),z = runif(11))
b = data.frame(x = seq(0,y = runif(11))
#generate ggplot
library(ggplot2)
p1 = ggplot(a,aes(x = x,y = y,fill = z)) + geom_raster() + coord_fixed()
p2 = ggplot(b,y = y)) + geom_line()
#align with cowplot => alignment not working if p1 is squared.
library(cowplot)
plot_grid(p1,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,ncol = 1)
egg::ggarrange(p1,1))
--
另一种策略是不对 p1 使用 coord_fixed,使用导出文件维度并以“正确”维度导出
p1bis = ggplot(a,fill = z)) + geom_raster()
plot_grid(p1bis,axis = 'lr',rel_heights = c(4,1))
ggsave("temp.pdf",width = 18,height = 24.5,units = "cm")
但是我不清楚如何以动态方式计算导出PDF文档的宽高比。有没有办法提取(以npc为单位?)panel.border的宽度和高度?
--
我还遇到了 ggh4x
包,它和 egg 一样,包含一个设置面板大小的函数。但是和patchwork结合时,panelsize信息好像丢失了
library(ggh4x)
p1f = p1bis + force_panelsizes(rows = unit(10,"cm"),cols = unit(10,"cm"))
p2f = p2 + force_panelsizes(cols = unit(10,rows = unit(3,"cm"))
p1f + p2f + p2f + plot_layout(nrow = 3)
您还有其他想法吗?我是否遗漏了一些微不足道的东西?
感谢您的时间!
解决方法
固定方面图的情况在{patchwork} website 中描述:
组装图的一个特殊情况是处理 固定方面图,例如用 coord_fixed() 创建的图, coord_polar() 和 coord_sf()。不能同时 分配偶数尺寸并对齐固定纵横图。
...
需要哪种解决方案可能取决于具体用例。
在您的情况下,一种方法是嵌套图:
library(ggplot2)
library(patchwork)
p22 <- p2 + p2 + plot_layout(nrow = 2)
p1 + p22 + plot_layout(nrow = 2)
由 reprex package (v0.3.0) 于 2021 年 5 月 11 日创建
这无法对高度进行微调控制,但我们可以使用 plot_spacer()
s 调整嵌套图:
library(patchwork)
p22 <- plot_spacer() + p2 + plot_spacer() + p2 + plot_spacer() + plot_layout(heights = c(1,2,1,1))
p1 + p22 + plot_layout(nrow = 2)
由 reprex package (v0.3.0) 于 2021 年 5 月 11 日创建