[英]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.