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

如何在R中用自定义函数生成的多张绘图创建ioslides演示文稿

解决方案

你遇到的是knitr渲染R Markdown时默认不捕获循环中生成的所有基础绘图的问题,用以下两种方案即可解决,无需修改原有基础绘图核心逻辑:

方案1:最简修复(所有图放在同一页幻灯片)

只需要给绘图的代码块添加fig.keep = "all"参数,强制knitr保留代码运行过程中生成的所有绘图,同时可以调整fig.height适配上下排列的双图布局,避免内容挤压:

---
title: "My presentation"
output: ioslides_presentation
---

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

PLOTS

list_genes <- c("GEN1", "GEN2", "GEN3")


myfunction <- function(x,y){
  
  for(gene in list_genes){
    # This to draw both plots
      par(mfrow=c(2,1))  
      
      stripchart(x, method="jitter", vertical=F, main=paste0("Plot of ", gene))
      
      hist(x, main=paste0("Plot of ", gene))
  }
}

myfunction(x=c(1,5,6,2,4,30,23,12,45))
## 方案2:每个基因的绘图单独占一页幻灯片
如果需要自动给每个基因生成独立的幻灯片页,可搭配`results="asis"`参数,在循环中动态输出幻灯片标题:
```r
---
title: "My presentation"
output: ioslides_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
list_genes <- c("GEN1", "GEN2", "GEN3")

myfunction <- function(x, gene){
    par(mfrow=c(2,1))  
    stripchart(x, method="jitter", vertical=F, main=paste0("Plot of ", gene))
    hist(x, main=paste0("Plot of ", gene))
}
x_vec <- c(1,5,6,2,4,30,23,12,45)
for(gene in list_genes){
  # 动态生成幻灯片标题
  cat(paste0("\n\n## Plot for ", gene,"\n\n"))
  myfunction(x = x_vec, gene = gene)
}
> 两种方案都不需要切换到ggplot2,适配你已有的基础绘图代码即可正常生成所有绘图。

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

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

最近更新时间:2026.09.26 08:45:08