0

与这篇文章非常相似。但是,我的图比一页上的图多,导致剩余的图在按下 Knit 后被切断。有谁知道如何通过在下一页绘制其他图来解决这个问题?

title: 'title'
author: "--"
date: "`r Sys.Date()`"
output: pdf_document
header-includes:
  - \usepackage{subfig}
  - \usepackage{float}

## To make the example more reproducible ##

```{r echo=FALSE, message=FALSE}
knitr::opts_chunk$set(fig.width=6, fig.height=9, fig.show="hold", 
hightligh=TRUE, warnings=TRUE, error=FALSE, cache=FALSE, echo=FALSE, 
dpi=100)

library(ggplot2)

```

```{r test, fig.cap='A collection of figs', fig.subcap= "-", out.width="49%", fig.asp=1, fig.ncol = 2, fig.show = 
"asis", fig.align="center"}

       for (ii in 1:10) {
       qplot(1:3, 1:3, main=ii)
       }

```

## this part is only to resemble the answer by *Michael Harper* in the post mentioned before and should be uncommented to replicate (google maps API needed) ## 

# ```{r}
# locations <- c("Southampton, UK", "London, UK", "Bristol, UK", 
# "Birmingham, UK", "Liverpool, UK", "Southampton, UK", "London, UK", 
# "Bristol, UK", "Birmingham, UK", "Liverpool, UK") 
# ggmap::register_google(key = "....")
# ```

# ```{r fig-sub-2, fig.cap='A collection of maps', fig.subcap= locations, 
# out.width='.49\\linewidth', fig.asp=1, fig.ncol = 2}
# library(ggmap)
# lapply(locations, function(x) 
# ggmap(get_map(x))
# )
# ```

Michael Harper一篇文章中的回答让我走得很远,但并没有达到情节数量超过适合一页的情节数量的地步。

从上面的代码中输出仅显示 10 个图中的 6 个

4

1 回答 1

0

为了完整起见,我将展示如何使用此处发布的@MichaelHarper 的解决方案来解决问题。

---
title: "tmp"
author: "Kevin Ouwerkerk"
date: "4-5-2020"
output: pdf_document
header-includes:
  - \usepackage{subfig}
  - \usepackage{float}

---

```{r echo=FALSE, message=FALSE}
library(ggplot2)

knitr::opts_chunk$set(warnings=TRUE, error=FALSE, cache=FALSE, echo=FALSE, 
dpi=100)

plots <- list()
```

```{r test}
   for (ii in 1:10) {
   plots[[ii]] <- qplot(1:3, 1:3, main=ii)
   }
```

```{r split-function}
knitr::opts_chunk$set(echo = FALSE)

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"}

splitSubFig(plots, caption = "Your Caption", maxlength = 6)

```

如果您有一个很长的标题并且您收到错误,您可以在函数中的参数之后的代码块名称Error in dirname(name) : path too long中删除{{caption}}textcat

于 2020-05-19T18:42:50.067 回答