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

如何用cowplot的plot_grid让单图在2列布局行中居中且尺寸一致?

解决cowplot plot_grid三图居中布局问题

要让第三张图在2×2布局的第二行居中,同时保持和前两张图尺寸一致,有两种简单可行的方法:

方法1:嵌套plot_grid + 空白占位图

先把前两张图组成第一行,再给第三张图左右添加空白占位图实现居中,最后把两行组合起来:

library(ggplot2)
library(cowplot)

p1 <- ggplot(mtcars, aes(disp, mpg)) + geom_point()
p2 <- ggplot(mtcars, aes(disp, mpg)) + geom_point()
p3 <- ggplot(mtcars, aes(disp, mpg)) + geom_point()

# 创建完全空白的占位图
blank <- ggplot() + theme_void()

# 组合第一行(p1+p2)
top_row <- plot_grid(p1, p2, ncol = 2)
# 组合第二行:左右空白+居中的p3,宽度比例保证p3和p1/p2尺寸一致
bottom_row <- plot_grid(blank, p3, blank, ncol = 3, rel_widths = c(0.5, 1, 0.5))

# 把两行拼起来
plot_grid(top_row, bottom_row, ncol = 1, rel_heights = c(1, 1))

方法2:使用plot_grid的layout_matrix自定义布局

通过layout_matrix指定第三张图横跨第二行的两个位置,配合宽度设置避免拉伸:

# 创建完全空白的占位图
blank <- ggplot() + theme_void()

plot_grid(
  p1, p2,
  p3, blank,
  ncol = 2,
  # 定义布局:第二行的两个位置都对应p3
  layout_matrix = rbind(
    c(1, 2),
    c(3, 3)
  ),
  # 保证p3宽度和p1/p2一致
  rel_widths = c(1, 1),
  # 隐藏空白图的占位痕迹
  labels = NULL
)

原理说明

原命令plot_grid(p1, p2, p3, ncol = 2)会生成2行2列的网格,按顺序填充p1(1,1)、p2(1,2)、p3(2,1),第四位留空导致右下角空白。通过嵌套布局或自定义矩阵,我们让p3在第二行占据中间1份宽度,左右用空白填充,既实现居中,又维持了和前两张图相同的尺寸。

内容的提问来源于stack exchange,提问作者Maarölli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:35:31