ggplot多面板组合:如何保持绘图区域尺寸一致?
解决三面板ggplot图绘图区域不一致问题
问题根源:移除前两张图的x轴刻度与标签后,原本分配给x轴元素的空间被合并到绘图区域,导致前两张图的绘图高度大于第三张图。
解决方案1:使用垂直对齐参数
在ggarrange中添加align = "v"参数,强制三张图垂直方向对齐,确保绘图区域高度一致。修改后的代码如下:
library(ggplot2) library(ggpubr) # Generate synthetic data set.seed(123) df1 <- data.frame(x = 1:10, y = rnorm(10)) df2 <- data.frame(x = 1:10, y = rnorm(10)) df3 <- data.frame(x = 1:10, y = rnorm(10)) # Create plots p1 <- ggplot(df1, aes(x, y)) + geom_point() + labs(title = "Plot 1") p2 <- ggplot(df2, aes(x, y)) + geom_point() + labs(title = "Plot 2") p3 <- ggplot(df3, aes(x, y)) + geom_point() + labs(title = "Plot 3") # Arrange plots with vertical alignment ggarrange( p1 + rremove(c("x.text", "xlab")), p2 + rremove(c("x.text", "xlab")), p3, labels = c("A", "B", "C"), common.legend = TRUE, legend = "bottom", nrow = 3, align = "v" # 关键参数:垂直对齐 )
解决方案2:统一设置主题边距
如果垂直对齐效果不理想,可以手动统一三张图的绘图边距,让前两张图的下边距预留出与第三张图x轴相同的空间:
# 定义统一的主题设置 common_theme <- theme( plot.margin = margin(t = 5, r = 5, b = 20, l = 5, unit = "pt") ) # 给前两张图移除x轴元素并应用统一边距,第三张图直接应用边距 p1_adj <- p1 + rremove(c("x.text", "xlab")) + common_theme p2_adj <- p2 + rremove(c("x.text", "xlab")) + common_theme p3_adj <- p3 + common_theme ggarrange( p1_adj, p2_adj, p3_adj, labels = c("A", "B", "C"), common.legend = TRUE, legend = "bottom", nrow = 3 )
两种方法都能保证三张图的绘图区域高度一致,让整体布局更协调。
内容的提问来源于stack exchange,提问作者Yujie Liu
相关产品推荐
相关产品推荐

