mho*_*ovd 5 r ggplot2 patchwork
我遇到了使用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)
Run Code Online (Sandbox Code Playgroud)

# 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)
Run Code Online (Sandbox Code Playgroud)

# 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)
Run Code Online (Sandbox Code Playgroud)

如何使用拼凑来改进布局?第二行中的图应该像第一行一样具有第一行的一半宽度,但所有图的纵横比都应为 1。
我也曾在使用拼凑而成的具有纵横比的图形上遇到过很多困难。
首先我给你解决方案,下面我给你更多解释为什么我认为这段代码重现了正确的数字。
design <- "
33
12
"
plotlist$fig2 + plotlist$fig3 + plotlist$fig1 +
plot_layout(
design = design,
heights = unit(c(2,-1),c("null","null"))
)
Run Code Online (Sandbox Code Playgroud)
我的一个关键见解是,可以在和参数中指定-1 NULL单位,它指定具有这种单位的列和行应该适应具有固定纵横比的图形的尺寸(我认为......)。heightwidth
例如,在下面的代码中,我举了一个示例,其中我想要保留一个长宽比为 1 的图形,但我希望能够指定其他列的宽度。这里我指定中间的列应该有3厘米的宽度(至少当我截图时),右列应该尊重图形的纵横比(例如-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")))
Run Code Online (Sandbox Code Playgroud)
编辑:从 patchwork 版本 1.1.3 开始,这种行为现在也正式记录在小插图中:https ://patchwork.data-imaginist.com/articles/guides/layout.html#fixed-aspect-plots
因此,为了生成您的图形,我指定最后一行应遵循图形的纵横比,同时指定第一行应为高度的两倍。