如何在ggplot的patchwork/cowplot网格中仅对齐绘图外边界?
解决patchwork组合绘图因长图例导致的布局空隙问题
问题描述
我有若干带冗长图例的绘图(以下为使用iris数据集的示例,非实际绘图):
library(tidyverse) library(patchwork) theme_template <- theme_classic() + theme( # add border all around plot panel.border = element_rect(colour = "black", fill = NA, linewidth = 1) ) p1 <- iris %>% ggplot(aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + geom_point() + scale_color_discrete( breaks = c("setosa", "versicolor", "virginica"), labels = c("Setosa", "Versicolor", "VirginicaVirginicaVirginicaVirginica") ) + theme_template p2 <- iris %>% ggplot(aes(x = Petal.Length, y = Petal.Width, color = Species)) + geom_point() + theme_template p3 <- iris %>% ggplot(aes(x = Species, y = Sepal.Length)) + geom_violin(aes(fill = Species), scale = "width") + geom_boxplot(width = .2, outlier.color = NA, fill = "black") + theme_template + theme( legend.position = "none", aspect.ratio = 1 ) p4 <- iris %>% ggplot(aes(x = Species, y = Petal.Width)) + geom_violin(aes(fill = Species), scale = "width") + geom_boxplot(width = .2, outlier.color = NA, fill = "black") + theme_template + theme( legend.position = "none", aspect.ratio = 1 ) p1 + p2 + p3 + p4 + plot_layout(ncol = 2, heights = c(1, 1, 1, 1))
使用patchwork组合后,因冗长图例导致底部两个绘图间存在巨大空隙。受实际数据集和格式代码限制,我无法合并图例、调整图例位置或缩短图例文字,希望实现仅对齐绘图外边界的布局,请问是否可行?
解决方案
可行,通过patchwork的align参数可以强制对齐绘图面板的外边界(即实际的绘图区域,不含图例),避免长图例干扰其他绘图的布局。
方法1:修改原布局代码
替换原有的布局代码,添加plot_annotation(align = "panel"):
p1 + p2 + p3 + p4 + plot_layout(ncol = 2, heights = c(1, 1)) + # 修正heights参数,ncol=2时只需指定两行高度比例 plot_annotation(align = "panel")
方法2:使用wrap_plots函数
更简洁的方式是直接用wrap_plots并指定align="panel":
wrap_plots(p1, p2, p3, p4, ncol = 2, align = "panel")
两种方法都会让所有绘图的面板区域精准对齐,长图例仅在自身绘图的范围内扩展,不会挤压或拉伸其他绘图的空间,从而消除底部绘图间的空隙。
内容的提问来源于stack exchange,提问作者ErwinTATP
相关产品推荐
相关产品推荐

