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

如何在R Markdown Word输出中实现kable表格与图表并排?

在R Markdown Word输出中实现图表与kable表格并排

要在R Markdown生成的Word文档里让图表和kable表格并排显示,针对Word输出的特性,推荐两种实用方案,你可以根据是否需要编辑表格来选择:

方法一:用officer创建原生Word并排布局(表格可编辑)

这种方法能生成原生的Word表格和图片,后续可以直接在Word里编辑表格内容,适合需要后续修改的场景。需要用到officer(控制Word文档结构)和flextable(处理表格格式)两个包:

步骤与代码示例

---
title: "图表与表格并排示例"
output: word_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
# 加载所需包
library(officer)
library(flextable)
library(ggplot2)

# 模拟你的数据和图表(替换成你自己的res对象即可)
set.seed(123)
res <- list(
  actzone = data.frame(
    Zone = c("Zone1", "Zone2"),  # 模拟你的2列表格
    Value = c(45, 55)
  ),
  actzoneBar = ggplot(res$actzone, aes(x = Zone, y = Value)) +
    geom_bar(stat = "identity", fill = "#2E86AB") +
    theme_minimal() +
    labs(title = "区域占比")
)
# 创建一个临时Word文档对象
doc <- read_docx()

# 添加两列布局的段落区域:调整widths参数控制两列宽度比例
doc <- body_add_section(
  doc,
  cols = section_columns(widths = c(3, 2), space = 0.2)  # 图表列宽3,表格列宽2,间隔0.2英寸
)

# 把图表插入第一列
doc <- body_add_gg(doc, value = res$actzoneBar, width = 3, height = 4)

# 把kable表格转成flextable,插入第二列
ft_table <- flextable(res$actzone) %>%
  autofit() %>%  # 自动适配列宽
  set_table_properties(layout = "autofit")
doc <- body_add_flextable(doc, value = ft_table)

# 输出到当前文档
print(doc, target = tempfile(fileext = ".docx"))

注意点

  • 可以通过调整section_columns里的widths参数来适配你的图表和表格尺寸;
  • 如果你的图表不是ggplot,而是其他类型(比如base plot),可以用body_add_img替换body_add_gg,先把图表保存为临时图片再插入。

方法二:用gridExtra组合成单个图形(快速实现,表格不可编辑)

如果不需要编辑表格,只想快速实现并排效果,可以把表格转换成图形元素,和原图组合成一个整体图形输出,代码更简洁:

步骤与代码示例

---
title: "图表与表格并排示例"
output: word_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(gridExtra)
library(grid)
library(ggplot2)

# 模拟你的数据和图表
set.seed(123)
res <- list(
  actzone = data.frame(
    Zone = c("Zone1", "Zone2"),
    Value = c(45, 55)
  ),
  actzoneBar = ggplot(res$actzone, aes(x = Zone, y = Value)) +
    geom_bar(stat = "identity", fill = "#2E86AB") +
    theme_minimal() +
    labs(title = "区域占比")
)
# 把表格转换成图形对象
table_grob <- tableGrob(res$actzone, rows = NULL, theme = ttheme_minimal())

# 并排显示图表和表格:调整widths参数控制比例
grid.arrange(res$actzoneBar, table_grob, ncol = 2, widths = c(3, 2))

优缺点

  • 优点:代码简单,不需要额外处理Word布局;
  • 缺点:表格是图形的一部分,无法在Word里编辑内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:30:42