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

如何用grid.arrange拼接多个ggplot并添加顶部、右侧灰色文本框

ggplot多图拼接加顶部/右侧灰色文本框通用方案

方案1:使用patchwork包实现(推荐,灵活度更高)

patchwork是专门针对ggplot多图拼接开发的包,调整标注、布局比grid.arrange简便很多,通用实现代码如下:

# 加载依赖包
library(ggplot2)
library(patchwork)
library(grid)
library(gridExtra)

# ---------- 1. 先构造示例ggplot(替换成你自己的8张图即可)
plt_list <- lapply(1:8, function(x) {
  ggplot(mtcars, aes(mpg, disp)) + geom_point() + labs(title = paste0("图",x))
})

# ---------- 2. 构造带灰色背景的文本grob函数(通用,可直接复用)
make_gray_text_grob <- function(text, fontsize = 20, fill = "gray90", rot = 0) {
  # 先画灰色背景矩形
  bg <- rectGrob(gp = gpar(fill = fill, col = NA))
  # 再画文本
  txt <- textGrob(text, gp = gpar(fontsize = fontsize), rot = rot)
  # 组合成复合grob
  grobTree(bg, txt)
}

# 生成你需要的顶部、右侧、左侧、底部标注
top_grob <- make_gray_text_grob("XL1 Gel vs No Gel", fontsize = 25)
right_grob <- make_gray_text_grob("右侧标注内容", fontsize = 25, rot = 270) # rot控制旋转角度
left_grob <- make_gray_text_grob("IP/Input (log2)", fontsize = 25, rot = 90)
bottom_grob <- make_gray_text_grob("IP/Input (log2)", fontsize = 25)

# ---------- 3. 拼接主图+标注
# 先按2行4列拼接8张主图
main_plots <- wrap_plots(plt_list, ncol = 4, nrow = 2)
# 再拼接所有标注,调整宽度/高度比例
full_plot <- top_grob + 
  (left_grob + main_plots + right_grob) + 
  bottom_grob +
  # 调整布局比例,数值根据需要调整即可
  plot_layout(
    ncol = 1,
    heights = c(0.1, 0.8, 0.1), # 顶部标注高度:主图高度:底部标注高度
    widths = c(0.1, 0.8, 0.1) # 左侧标注宽度:主图宽度:右侧标注宽度
  )

# 输出结果
full_plot

方案2:适配你原有grid.arrange代码的修改方案

如果不想换包,只需要在你原有代码基础上,补充灰色文本grob和调整布局参数即可,修改后代码如下:

library(grid)
library(gridExtra)
library(ggplot2)

# 复用上面的灰色文本grob生成函数
make_gray_text_grob <- function(text, fontsize = 20, fill = "gray90", rot = 0) {
  bg <- rectGrob(gp = gpar(fill = fill, col = NA))
  txt <- textGrob(text, gp = gpar(fontsize = fontsize), rot = rot)
  grobTree(bg, txt)
}

# 生成各位置标注
yleft <- make_gray_text_grob("IP/Input (log2)", rot = 90, fontsize = 25)
bottom <- make_gray_text_grob("IP/Input (log2)", fontsize = 25)
top <- make_gray_text_grob("XL1 Gel vs No Gel", fontsize = 25)
right <- make_gray_text_grob("你的右侧标注内容", rot = 270, fontsize = 25)

# 调整grid.arrange布局矩阵,预留顶部、右侧、底部、左侧位置
lay <- rbind(
  c(NA, 1, 1, 1, 1, NA), # 顶部标注
  c(2, 3, 4, 5, 6, 7), # 第二行:左标注+4张主图+右标注
  c(2, 8, 9, 10, 11,7), # 第三行:左标注+4张主图+右标注
  c(NA, 12,12,12,12,NA) # 底部标注
)

# 按布局传入所有grob
grid.arrange(
  top,
  yleft,
  XL1_above_gel_plot, plot_1_gel_rep, XL1_plot_log1, XL1_vs_XL2_nogel_log1,
  right,
  plot_1_gel_rep, XL2_above_gel_plot, XL2_vs_XL1_nogel_log1, XL2_plot_log1,
  bottom,
  layout_matrix = lay,
  # 调整各行列的宽高比例
  widths = c(0.1, rep(0.2,4), 0.1),
  heights = c(0.1, 0.4, 0.4, 0.1)
)

参数调整说明

  • 灰色深浅可以修改make_gray_text_grob里的fill参数,gray90是浅灰,数值越小颜色越深
  • 标注大小、旋转角度分别调整fontsize、rot参数即可
  • 布局的宽高比例根据你实际的出图尺寸调整对应位置的数值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:06:03