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

如何减小R语言ggplot2+patchwork拼接时行标题与子图的间距

解决方法

你需要从两个维度调整留白:一是减小标题图本身的底部边距,二是控制patchwork布局中标题行的高度占比,修改后的代码如下:

library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) +
  geom_point(aes(mpg, disp)) +
  ggtitle("Plot 1") +
  # 同时可以把子图的顶部边距也调小,进一步缩小间距
  theme(plot.margin = margin(t = 5, unit = "pt"))

p2 <- ggplot(mtcars) +
  geom_boxplot(aes(gear, disp, group = gear)) +
  ggtitle("Plot 2") +
  theme(plot.margin = margin(t = 5, unit = "pt"))

p3 <- ggplot(mtcars) +
  geom_point(aes(hp, wt, colour = mpg)) +
  ggtitle("Plot 3") +
  theme(plot.margin = margin(t = 5, unit = "pt"))

p4 <- ggplot(mtcars) +
  geom_bar(aes(gear)) +
  facet_wrap(~cyl) +
  ggtitle("Plot 4") +
  theme(plot.margin = margin(t = 5, unit = "pt"))

# 调整标题图的底部边距,负数值可以让标题更贴近下方子图
ggplot() +
  annotate(geom = "text", x = 1, y = 1, label = "Predictions on Dataset 1",size=8) +
  theme_void() +
  theme(plot.margin = margin(b = -10, unit = "pt")) -> title1
ggplot() +
  annotate(geom = "text", x = 1, y = 1, label = "Predictions on Dataset 2",size=8) +
  theme_void() +
  theme(plot.margin = margin(b = -10, unit = "pt")) -> title2


title1 /
  (p1 | p2) /
  title2 /
  (p3 | p4) +
  plot_annotation(
    tag_levels = list(c("","A.1) Model Name 1", "B.1) Model Name 2", "","A.2) Model Name 1", "B.2) Model Name 2")),
    theme = theme(plot.title = element_text(size = 24))
  ) &
  # 控制四行的高度比例,数值越小对应行的高度越低,留白越少
  plot_layout(heights = c(0.08, 1, 0.08, 1))

参数调整说明

  • margin(b = -10, unit = "pt"):b对应底部边距,数值越小(越负),标题和下方子图的间距越小,可根据实际显示效果调整数值
  • heights = c(0.08, 1, 0.08, 1):四个数值依次对应title1、p1+p2、title2、p3+p4四行的高度占比,调小第一个、第三个数值可以压缩标题行的多余空白

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:45:00