[英]How to create a presentation in R with several plots obtained by a function?
我創建了一個函數,根據列表為您提供所需的繪圖數量。
這是我創建的示例。
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))
我的最終目標是使用我從函數生成的所有圖創建一個演示文稿(自動)。
但是,如果我嘗試創建一個ioslides_presentation
,它們不會出現(只有第一個和第二個的一點)。
---
title: "My presentation"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## PLOTS
```{r}
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))
```
該代碼是我原始函數的一個小例子,但足以向您展示我的問題。 我試圖將繪圖保存到對象中,但由於它是基礎 R,我不能(或者至少,它不能正常工作)。 我知道我可以用ggplot2
做到這一點,但是,我想在這里問一下,以防萬一有人知道如何在這種情況下進行演示,然后再更改完整的原始功能。
有誰知道如何解決它?
首先十分感謝
問候
有幾種方法可以得到這個。 恕我直言,最簡單的方法是從函數中取出mfrow
或mfcol
調用,並為所有圖創建一個全局調用,例如:
---
title: "My presentation"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## PLOTS
```{r}
list_genes <- c("GEN1", "GEN2", "GEN3")
myfunction <- function(x,y){
for(gene in list_genes){
stripchart(x, method = "jitter", vertical = FALSE,
main = paste0("Plot of ", gene))
hist(x, main = paste0("Plot of ", gene))
}
}
par(mfcol = c(2, 3))
myfunction(x = c(1, 5, 6, 2, 4, 30, 23, 12, 45))
```
附加說明:在R代碼中最好使用FALSE
而不是F
FALSE
是保留字,而F
是“脆弱的”,因為它可以重新定義。
感謝@tpetzoldt 和這篇文章,我找到了我需要的東西!
我不得不稍微改變一下函數並在循環內創建演示文稿的標題。
這是解決方案:
---
title: "Create a presentation with several plots"
output:
ioslides_presentation
---
```{r, echo=FALSE}
myfunction <- function(x, gene){
# 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))
}
```
```{r, echo=FALSE}
list_genes <- c("GEN1", "GEN2", "GEN3")
```
```{r, echo = FALSE, results = "asis"}
for(gene in list_genes){
cat("\n\n## Plot of ", gene, "\n\n")
myfunction(x=c(1,5,6,2,4,30,23,12,45), gene)
}
```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.