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

如何在R语言中将表格与多幅绘图合并为一幅组合图?

解决ggplot2绘图与kable表格合并的gList错误

错误原因

你遇到的Error in gList(...) : only 'grobs' allowed in "gList",是因为kable()和kable_styling()生成的是HTML/LaTeX格式的表格,并非grid包能识别的grob图形对象,而arrangeGrob()仅支持grob对象或ggplot对象(ggplot本质也是grob)。

解决方案1:使用gridExtra::tableGrob()转换数据框为grob

直接将处理好的数据框转换为tableGrob(grid兼容的表格对象),可自定义基础样式:

library(gridExtra)

# 处理数据并转换为tableGrob
table_grob <- tableGrob(
  FinalPitches %>% arrange(desc(Pitches)),
  col.names = c("Player Name", "Pitch Type", "Pitches", "Velocity", "Horizontal Break", "Vertical Break",
                "Spin Rate", "VAA", "Strike%","CSW%", "Whiff%", "Stuff+"),
  rows = NULL  # 移除默认行号
)

# 替换原third_arrange代码
third_arrange <- arrangeGrob(table_grob, nrow = 1)

解决方案2:用kableExtra::as_image()将kable表格转为ggplot对象

如果想保留kable的美化样式,可将表格转为图片格式的ggplot对象,再参与布局:

library(kableExtra)

# 将已美化的kable表格转为ggplot对象
table_plot <- table1 %>%
  as_image(width = 8, height = 2)  # 根据布局需求调整宽高

# 替换原third_arrange代码
third_arrange <- arrangeGrob(table_plot, nrow = 1)

完整合并代码(以方案1为例)

library(gridExtra)
library(ggplot2)

# 处理表格为grob对象
table_grob <- tableGrob(
  FinalPitches %>% arrange(desc(Pitches)),
  col.names = c("Player Name", "Pitch Type", "Pitches", "Velocity", "Horizontal Break", "Vertical Break",
                "Spin Rate", "VAA", "Strike%","CSW%", "Whiff%", "Stuff+"),
  rows = NULL
)

# 定义各行列布局
first_arrange <- arrangeGrob(
  BreakChart, LocationMap,
  nrow = 1, widths = c(0.40, 0.50)
)

second_arrange <- arrangeGrob(
  Even1, Ahead1, Behind1, TwoStrikes1,
  nrow = 1, widths = c(0.15, 0.15, 0.15, 0.15)
)

third_arrange <- arrangeGrob(table_grob, nrow = 1)

# 合并所有元素
combined_plot6 <- grid.arrange(
  first_arrange, second_arrange, third_arrange,
  ncol = 1, nrow = 3,
  heights = unit(c(1, 1, 0.5), "null")
)

print(combined_plot6)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:27:48