微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

合并和对齐 ggplot,包括一个可以控制其高度的正方形

如何解决合并和对齐 ggplot,包括一个可以控制其高度的正方形

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

我已经阅读了其他 SO 主题包括这个 (Vertically align of plots of different heights using cowplot::plot_grid() when using coord_equal())。

到目前为止:我可以对齐地块,包括方形地块(使用 eggpatchwork),但我无法调整面板的相对高度。 以下是我尝试过的(使用 cowploteggpatchwork 包)。

使用 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 日创建

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。