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

如何在Rmarkdown中实现图表与表格的并排显示?(支持导出至Word和Excel而非PDF)

Answer

Absolutely, this is totally feasible! Let's break down how to achieve side-by-side chart and table layouts for both Word and Excel outputs using R Markdown.

For Word Output

There are two reliable approaches here—one gives you fully formatted tables, the other is quicker for simpler use cases.

Approach 1: Using officer + flextable (Best for Formatted Tables)

This method lets you create a proper two-column layout in Word, with a high-quality plot and a neatly styled table. First, install the required packages:

install.packages(c("officer", "flextable", "ggplot2", "dplyr"))

Here’s a complete code example you can drop into your R Markdown document:

---
title: "Side-by-Side Plot & Table (Word)"
output: word_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(officer)
library(flextable)
library(ggplot2)
library(dplyr)

Side-by-Side Layout

We’ll create a sample dataset, build a plot and table, then insert them into a two-column section in Word:

# Sample data
sample_data <- mtcars %>% head(5) %>% select(mpg, cyl, disp)

# Create ggplot
car_plot <- ggplot(sample_data, aes(x = mpg, y = disp, color = factor(cyl))) +
  geom_point(size = 3) +
  labs(title = "MPG vs Engine Displacement") +
  theme_minimal()

# Create styled flextable
car_table <- flextable(sample_data) %>%
  theme_booktabs() %>%
  autofit()

# Build the Word document
doc <- read_docx() %>%
  body_add_par("Side-by-Side Visualization", style = "Heading 1") %>%
  # Start two-column section
  body_add_section(
    section_columns(widths = c(6, 6), space = 0.5, sep = FALSE)
  ) %>%
  # Insert plot into first column
  body_add_gg(car_plot, width = 5, height = 4) %>%
  # Insert table into second column
  body_add_flextable(car_table) %>%
  # End two-column section
  body_end_section()

# Export to Word
print(doc, target = "side_by_side_word.docx")

Approach 2: Using gridExtra (Quick & Simple)

If you don’t need highly formatted tables, you can combine the plot and table into a single graphic that renders side-by-side in Word:

install.packages("gridExtra")

# In your Rmd chunk:
library(gridExtra)
table_grob <- tableGrob(sample_data)
grid.arrange(car_plot, table_grob, ncol = 2, widths = c(1, 1))

This outputs a single image with both elements side by side, which works seamlessly in Word.

For Excel Output

R Markdown doesn’t have a native Excel output format, but you can programmatically generate an Excel file with side-by-side plot and table using the openxlsx package. Install it first:

install.packages(c("openxlsx", "ggplot2", "dplyr"))

Here’s how to do it:

---
title: "Side-by-Side Plot & Table (Excel)"
output: html_document # Or any output, since we'll generate Excel via code
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(openxlsx)
library(ggplot2)
library(dplyr)

Export to Excel with Side-by-Side Layout

# Reuse sample data and plot from earlier
sample_data <- mtcars %>% head(5) %>% select(mpg, cyl, disp)
car_plot <- ggplot(sample_data, aes(x = mpg, y = disp, color = factor(cyl))) +
  geom_point(size = 3) +
  labs(title = "MPG vs Engine Displacement") +
  theme_minimal()

# Create Excel workbook
wb <- createWorkbook()
addWorksheet(wb, "Data & Plot")

# Write table to cells A1:C6
writeData(wb, sheet = "Data & Plot", x = sample_data, startCol = 1, startRow = 1)

# Insert plot starting at cell E1 (adjacent to the table)
insertPlot(wb, sheet = "Data & Plot", plot = car_plot, startCol = 5, startRow = 1, width = 6, height = 4)

# Save the Excel file
saveWorkbook(wb, "side_by_side_excel.xlsx", overwrite = TRUE)

When you knit the Rmd, this code will generate an Excel file where the table is on the left and the plot is on the right.

Key Notes

  • For Word, the officer method gives you the most control over formatting and layout.
  • For Excel, you’re generating the file directly via code—you can adjust the startCol/startRow parameters to tweak the positioning as needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 04:44:09