You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使ggplot2组合图中各个分面(facet)尺寸完全一致?

解决ggplot2+patchwork组合图中分面尺寸不一致的问题

现有使用ggplot2和patchwork包绘制组合图的R代码如下:

library(ggplot2)
library(patchwork)
p1 <- ggplot(data = mtcars, aes(x = disp, y = mpg, color=as.factor(carb))) + geom_point()
p1 <- p1 + facet_wrap(~vs, ncol=1)

p2 <- ggplot(data = mtcars, aes(x = disp, y = mpg ,color=as.factor(carb))) + geom_point()
p2 <- p2 + facet_wrap(~carb)

combined <- p1 + p2 +
  plot_layout(ncol = 2) +
  plot_annotation(tag_levels = 'A')

组合图

当前图中A区域的分面宽度大于B区域的分面,需将所有分面调整为完全相同的尺寸,可通过以下两种方法解决:

方法1:用patchwork的align参数强制对齐坐标轴

在plot_layout中添加align = "hv"参数,强制水平和垂直方向对齐两个图的坐标轴,分面尺寸会自动匹配:

combined <- p1 + p2 +
  plot_layout(ncol = 2, align = "hv") +
  plot_annotation(tag_levels = 'A')

方法2:统一坐标轴范围并固定分面面板比例

如果需要更精准的控制,可手动统一x、y轴范围,再通过theme()固定面板的宽高比:

# 获取统一的坐标轴范围
x_range <- range(mtcars$disp)
y_range <- range(mtcars$mpg)

# 重新绘制p1,统一坐标轴并设置面板比例
p1 <- ggplot(data = mtcars, aes(x = disp, y = mpg, color=as.factor(carb))) + 
  geom_point() +
  facet_wrap(~vs, ncol=1) +
  coord_cartesian(xlim = x_range, ylim = y_range) +
  theme(panel.spacing = unit(1, "lines"), aspect.ratio = 1)

# 重新绘制p2,保持和p1一致的设置
p2 <- ggplot(data = mtcars, aes(x = disp, y = mpg ,color=as.factor(carb))) + 
  geom_point() +
  facet_wrap(~carb) +
  coord_cartesian(xlim = x_range, ylim = y_range) +
  theme(panel.spacing = unit(1, "lines"), aspect.ratio = 1)

# 组合图形
combined <- p1 + p2 +
  plot_layout(ncol = 2) +
  plot_annotation(tag_levels = 'A')

说明:方法1操作简单,适合大部分场景;方法2通过固定坐标轴范围和面板比例,能完全保证所有分面的尺寸一致,适合对布局精度要求较高的情况。

内容的提问来源于stack exchange,提问作者curious

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:45:20