Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
循环浏览GGPlot列表,并使用Knitr为每个图提供一个图形标题_R_Ggplot2_R Markdown_Knitr_Pandoc - Fatal编程技术网

循环浏览GGPlot列表,并使用Knitr为每个图提供一个图形标题

循环浏览GGPlot列表,并使用Knitr为每个图提供一个图形标题,r,ggplot2,r-markdown,knitr,pandoc,R,Ggplot2,R Markdown,Knitr,Pandoc,我正在使用ggplot2创建一系列绘图。其中每一个都是以编程方式命名的,我希望使用这些名称为每个图形提供自己的图形标题。我想从列表中提取姓名,并将其动态传递给fig.cap 有办法做到这一点吗?这是一个MCVE,您可以在列表和各个绘图之间切换,以查看图形消失或显示: --- output: pdf_document --- ```{r, include = FALSE} library(ggplot2) library(knitr) opts_chunk$set(echo=FALSE) ```

我正在使用ggplot2创建一系列绘图。其中每一个都是以编程方式命名的,我希望使用这些名称为每个图形提供自己的图形标题。我想从列表中提取姓名,并将其动态传递给fig.cap

有办法做到这一点吗?这是一个MCVE,您可以在列表和各个绘图之间切换,以查看图形消失或显示:

---
output: pdf_document
---

```{r, include = FALSE}
library(ggplot2)
library(knitr)
opts_chunk$set(echo=FALSE)
```

```{r}
## Plot 1
listOfPlots <- list(
  # Plot 1
  ggplot(data = diamonds) +
    geom_point(aes(carat, price)),

  ## Plot 2
  ggplot(data = diamonds) +
    geom_point(aes(carat, depth))
)

names(listOfPlots) <- c("This is caption 1", "This is caption 2")
```


```{r, fig.cap = c("This is caption 1", "This is caption 2"), echo=TRUE}

listOfPlots

# listOfPlots$`This is caption 1`
# listOfPlots$`This is caption 2`
```
---
输出:pdf\U文件
---
```{r,include=FALSE}
图书馆(GG2)
图书馆(knitr)
选择块$set(echo=FALSE)
```
```{r}
##地块1

ListofPlot如果要给它们自己的标题,R标记中的图之间需要有空格。如所述,这里的技巧是在两个图像之间添加一些换行符

```{r, fig.cap=c("Caption 1", "Caption 2")} 
listOfPlots[[1]]
cat('\n\n') 
listOfPlots[[2]]
``` 
注意,仅用于返回绘图本身

使用循环 假设您正在寻找一种更通用的方法,该方法适用于任何长度的列表,我们可以使用循环自动创建图之间的换行符。请注意,区块标题中需要
results=“asis”

```{r, fig.cap=c("Caption 1", "Caption 2"), echo=FALSE, results="asis"} 

for(plots in listOfPlots){
  print(plots)
  cat('\n\n') 
}

``` 


最后,您可能希望在标题中直接使用列表的名称。语法
{r,fig.cap=names(listOfPlots)}
可以实现这一点。

作为r标记提示,您可以在第一个代码块中使用
include=FALSE
参数来抑制任何输出。这意味着您不必将所有函数包装到
supersstartupmessages()
:。希望有帮助:)