首页 > 解决方案 > 当地块纵横比为 1 时将地块与拼凑组合

问题描述

我遇到了使用patchworkwhen组合图的问题theme(aspect.ratio = 1)。提供了几个例子:

library(tidyverse)
library(patchwork)

# Create the base plots
plotlist = list(
  fig1 = iris %>% 
    filter(Species == "setosa") %>% 
    ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point(),
  
  fig2 = iris %>% 
    filter(Species == "versicolor") %>% 
    ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point(),
  
  fig3 = iris %>% 
    filter(Species == "virginica") %>% 
    ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point()
)

# Here patchwork combines the plots nicely
plotlist$fig1 / (plotlist$fig2 + plotlist$fig3)


# However, if we change the aspect.ratio to 1 things don't look so nice anymore
plotlist = lapply(plotlist, function(x) {
  x + theme(aspect.ratio = 1)
})

# Notice the large gap between plots. Instead, I would like the plots in the second row to be almost directly under the first row.
plotlist$fig1 / (plotlist$fig2 + plotlist$fig3)

# I tried setting the margins to zero, but that doesn't change anything
plotlist = lapply(plotlist, function(x) {
  x + theme(plot.margin = margin(0, 0, 0, 0, unit = "pt"))
})

plotlist$fig1 / (plotlist$fig2 + plotlist$fig3)

如何使用拼凑改进布局?第二行的图应该是第一行宽度的一半,就像第一个图一样,但所有图的纵横比都应该是 1。

标签: rggplot2patchwork

解决方案


对于使用拼凑而成的具有纵横比的图形,我也遇到了很多困难。

首先我给你解决方案,下面我给你更多解释为什么我认为这段代码重现了正确的数字。

解决方案:

design <- "
  33
  12
    "
plotlist$fig2 + plotlist$fig3 + plotlist$fig1 + 
    plot_layout(
        design = design, 
        heights = unit(c(2,-1),c("null","null"))
  )

在此处输入图像描述


额外信息:

我的一个关键见解是可以在and参数中指定-1 NULL单位,它指定具有这种单位的列和行应该适应具有固定纵横比的图形的尺寸(我认为......)。heightwidth

例如,在下面的代码中,我给你一个例子,我想保留一个纵横比为 1 的图形,但我希望能够指定其他列的宽度。这里我指定中间列应该有 3cm 宽度(至少在我截屏时)右列应该尊重图形的纵横比(例如-1 NULL单位),左列可以填充剩余空间(例如1 NULL单位) .

library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear)) + theme(aspect.ratio = 1)
p1 + p1 + p2 + plot_layout(widths = unit(c(1,3,-1), c("null","cm","null")))

在此处输入图像描述

但我不能怪你不知道这一点,因为这似乎没有在任何地方记录。我自己也不完全理解它,我只是通过查看拼凑包的测试文件夹偶然发现了这个事实。

因此,为了生成您的图形,我指定最后一行应该尊重图形的纵横比,同时指定第一行应该是高度的两倍。


当心:

请注意,设计是经过仔细挑选的,由于某种原因,以下设计似乎不起作用:

design <- "
  11
  23
    "
plotlist$fig1 + plotlist$fig2 + plotlist$fig3 

这对我来说似乎是一个错误,我会将此作为问题报告给开发人员。


推荐阅读