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

R中使用gridExtra排布ggplot并自定义行列名、设置行名90度旋转

实现代码

基于你已使用的gridExtra和R原生grid包即可实现需求,无需额外安装其他依赖:

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

# ----------------------
# 替换此处为你自己的15个ggplot对象
# 示例用的测试图,你可以替换成自己的图表列表
p <- ggplot(mtcars, aes(wt, mpg)) + geom_line() + theme_bw()
# 图表列表按行排序:第1-3个为第一行(对应NBB行),4-6为第二行(MBB行),以此类推
plot_list <- rep(list(p), 15)
# ----------------------

# 定义行列名
cnames <- c('phi = 0.8', 'phi = 0.9', 'phi = 0.95')
rnames <- c("NBB", "MBB", "CBB", "MBB1", "CBB1")

# 构造标签元素:列标签不旋转,行标签旋转90度
col_labels <- lapply(cnames, function(x) textGrob(x, gp = gpar(fontsize = 12, fontface = "bold")))
row_labels <- lapply(rnames, function(x) textGrob(x, rot = 90, gp = gpar(fontsize = 12, fontface = "bold")))

# 1. 先排布核心图表网格
core_grid <- arrangeGrob(grobs = plot_list, ncol = 3, nrow = 5)

# 2. 拼接顶部列标签+核心图表
grid_with_col <- arrangeGrob(
  arrangeGrob(grobs = col_labels, nrow = 1),
  core_grid,
  nrow = 2,
  heights = c(0.08, 1) # 可调整数值修改列标签区域高度
)

# 3. 拼接左侧行标签+带列标签的图表网格,输出最终结果
final_grid <- grid.arrange(
  arrangeGrob(grobs = row_labels, ncol = 1),
  grid_with_col,
  ncol = 2,
  widths = c(0.08, 1) # 可调整数值修改行标签区域宽度
)

关键参数说明

  • rot = 90:控制行标签旋转90度,列标签未设置该参数,默认保持水平不旋转
  • 可修改gpar里的fontsize、fontface参数调整标签字号、字重
  • 调整heights/widths的数值可以修改标签区域和图表区域的占比,避免标签重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:36:04