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

如何用R的patchwork包让上方绘图居中且保持所有图尺寸一致?

使用patchwork实现居中且等尺寸的绘图排版

要实现「上方Plot A居中,下方并排Plot B和Plot C,且三个图尺寸完全相同」的排版,无需使用会缩小绘图的plot_spacer()原始写法,通过控制布局的宽度/高度比例即可实现:

初始绘图代码

library(patchwork)
library(tidyverse)

a <- ggplot(mtcars, aes(mpg, wt)) + geom_point() + ggtitle("Plot A")
b <- ggplot(mtcars, aes(drat, wt)) + geom_point() + ggtitle("Plot B")
c <- ggplot(mtcars, aes(cyl, wt)) + geom_point() + ggtitle("Plot C")

解决方案代码

# 构建顶部行:A居中,两侧空白宽度为B/C宽度的一半
top_row <- plot_spacer() + a + plot_spacer() +
  plot_layout(widths = c(1, 2, 1))

# 构建底部行:B和C宽度一致
bottom_row <- b + c + plot_layout(widths = c(2, 2))

# 组合上下行,设置高度一致保证图的高度相同
final_plot <- top_row / bottom_row +
  plot_layout(heights = c(2, 2))

# 查看结果
final_plot

原理说明

  • 通过plot_layout(widths = c(1,2,1))让顶部行的空白区域宽度为1,Plot A宽度为2,确保A的宽度和底部行中B/C的宽度(各2)完全匹配;
  • 用heights = c(2,2)设置上下行高度一致,保证三个图的高度也相同;
  • 最终三个图的宽、高完全一致,同时Plot A在顶部居中显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 11:57:05