fig.cap
被设计为采用单个参数,因此我们必须以编程方式为您想要的三个图中的每个图生成新的代码块。作为在这里解释,我们可以使用knit_expand
功能。我修改了提供的示例以包含子图标题以及从列表中打印绘图的方法。
我已经写了函数splitSubFig
这将限制每个图的子图数量。如果我们检查这个数字,它将创建一个新页面。请注意,您将需要使用results="asis"
在块头中创建数字:
---
output:
pdf_document: default
header-includes:
- \usepackage{subfig}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = F)
library(ggplot2)
library(knitr)
# Function to create a separate chunk to generate a plot for each item in list
splitSubFig <- function(plots, caption, maxlength) {
knitr::opts_knit$set(progress = FALSE, verbose = FALSE)
n <- length(plots)
numPages <- ceiling(n / maxlength)
splitPlots <- split(plots, rep(1:ceiling(n/maxlength), each=maxlength)[1:n])
for (page in 1:numPages) {
cat(
knit(text=knit_expand(
text=(
"```{r {{caption}}{{page}}, fig.cap='{{caption}}: {{page}}', fig.subcap=LETTERS[1:length(splitPlots[page])], out.width='8cm', fig.ncol=2, echo = FALSE, message = FALSE}
for(i in splitPlots[page]){
for(plots in i){
print(plots)
}
}
```"),
caption = caption,
page = LETTERS[page])))
}
}
```
```{r, results="asis"}
plots <- list(ggplot(data.frame(a = runif(50)), aes(x=a)) + geom_histogram(bins=10, fill = "red"),
ggplot(data.frame(a = runif(50)), aes(x=a)) + geom_histogram(bins=10),
ggplot(data.frame(a = runif(50)), aes(x=a)) + geom_histogram(bins=10),
ggplot(data.frame(a = runif(50)), aes(x=a)) + geom_histogram(bins=10),
ggplot(data.frame(a = runif(50)), aes(x=a)) + geom_histogram(bins=10),
ggplot(data.frame(a = runif(50)), aes(x=a)) + geom_histogram(bins=10, fill = "blue"),
ggplot(data.frame(a = runif(50)), aes(x=a)) + geom_histogram(bins=10),
ggplot(data.frame(a = runif(50)), aes(x=a)) + geom_histogram(bins=10),
ggplot(data.frame(a = runif(50)), aes(x=a)) + geom_histogram(bins=10),
ggplot(data.frame(a = runif(50)), aes(x=a)) + geom_histogram(bins=10))
splitSubFig(plots, caption = "Your Caption", maxlength = 6)
```
这个功能当然可以改进,但它应该适合您的需要!