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

如何在RMarkdown中同时使用results='asis'与fig.show='hold'?

解决RMarkdown循环生成标题与并排图表的顺序问题

问题根源在于fig.show='hold'会延迟所有图形输出至代码块结束,而results='asis'生成的标题文本是实时输出的,导致文本与图形顺序错位。

解决方法是放弃全局的fig.show='hold'参数,改为在循环内部将两张图表拼接为一个整体后再输出,确保每个标题对应紧跟其图表。

以下是两种可行的实现方式:

方法1:使用patchwork包(推荐,语法简洁)

patchwork是专门用于拼接ggplot图形的工具,语法直观:

---
title: "fig.show asis fix"
output: html_document
---

```{r, results = 'asis', echo = FALSE, warning = FALSE, message = FALSE}
library(ggplot2)
library(patchwork)

for (i in 1:3) {
  # 输出章节标题
  cat(paste('\n\n# Column', i, 'of the wonderful mtcars dataset\n\n'))
  
  # 创建两个图形
  box_plot <- ggplot(mtcars, aes_string(x = names(mtcars)[1])) + geom_boxplot()
  hist_plot <- ggplot(mtcars, aes_string(x = names(mtcars)[1])) + geom_histogram()
  
  # 并排拼接图形,宽度各占50%
  print(box_plot + hist_plot + plot_layout(widths = c(1, 1)))
}
## 方法2:使用gridExtra包
如果已经熟悉gridExtra,也可以用`grid.arrange`实现拼接:

```yaml
---
title: "fig.show asis fix"
output: html_document
---

```{r, results = 'asis', echo = FALSE, warning = FALSE, message = FALSE}
library(ggplot2)
library(gridExtra)

for (i in 1:3) {
  cat(paste('\n\n# Column', i, 'of the wonderful mtcars dataset\n\n'))
  
  box_plot <- ggplot(mtcars, aes_string(x = names(mtcars)[1])) + geom_boxplot()
  hist_plot <- ggplot(mtcars, aes_string(x = names(mtcars)[1])) + geom_histogram()
  
  # 按列排列两个图形,宽度均等
  print(grid.arrange(box_plot, hist_plot, ncol = 2, widths = c(1, 1)))
}
### 效果说明
两种方法都能实现:每个章节标题输出后,立即显示对应的两张并排图表,完全按照循环顺序呈现,不会出现标题与图表分离的问题。

内容的提问来源于stack exchange,提问作者qdread
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:45:57