我在使用 patchwork
合并图时遇到了问题当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。
最佳答案
对于使用拼凑而成的具有纵横比的数字,我也遇到了很多困难。
首先我给你解决方案,下面我给你更多解释为什么我认为这段代码重现了正确的数字。
解决方案:
design <- "
33
12
"
plotlist$fig2 + plotlist$fig3 + plotlist$fig1 +
plot_layout(
design = design,
heights = unit(c(2,-1),c("null","null"))
)
额外信息:
我的一个关键见解是可以在
height
中指定 -1 NULL 单位。和 width
参数指定具有这种单位的列和行应该适应具有固定纵横比的图形尺寸(我认为......)。例如,在下面的代码中,我举了一个例子,我想保留一个纵横比为 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")))
但我不能怪你不知道这一点,因为这似乎没有任何地方记录。我自己也不完全理解它,我只是通过查看 patchwork 包的 test 文件夹偶然发现了这个事实。
因此,为了生成您的图形,我指定最后一行应遵守图形的纵横比,同时指定第一行应为高度的两倍。
当心:
备注 该设计是精心挑选的,由于某种原因,以下设计似乎不起作用:
design <- "
11
23
"
plotlist$fig1 + plotlist$fig2 + plotlist$fig3
这对我来说似乎是一个错误,我会将其作为问题报告给开发人员。
关于r - 本地 block 纵横比为 1 时,将地 block 与拼凑而成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68376626/