简体   繁体   中英

Insert Pagebreak for Output after Code Chunk

I have a.Rmd file which I am converting to PDF. For layout reasons, I want to display the generated output plot of my code chunk on the next page even though it would just fit in underneath.

Normally with text etc. one would use

\pagebreak

But how can I signalize the code chunk that it should display its output on the next page? Thanks for helping!

You can write a knitr hook to set up a chunk option to do this.

So here I have modified the source chunk hook and created a chunk option next_page which, if TRUE , the output of that chunk will be on the next page.

---
title: "Chunk Output in Next page"
output: pdf_document
date: "2022-11-25"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

```{r, include=FALSE}
library(knitr)

default_source_hook <- knit_hooks$get('source')

knit_hooks$set(
  source = function(x, options) {
    if(isTRUE(options$next_page)) {
      paste0(default_source_hook(x, options),
        "\n\n\\newpage\n\n")
    } else {
      default_source_hook(x, options)
    }
  }
)
```

```{r, next_page=TRUE}
plot(mpg ~ disp, data = mtcars)
```

下一页中的块输出


I would recommend you to save the output in the file (png/jpeg/pdf) and then load it with the markdown or knitr . Such solution gives you a full control.

Automatic

I found alternative solution in rmarkdown-cookbook .

We generate a plot in this code chunk but do not show it:

```{r cars-plot, dev='png', fig.show='hide'}
plot(cars)
```

\newpage

![A nice plot.](\`r knitr::fig_chunk('cars-plot', 'png')\`)

Manual

```{r}
png("NAME.png") 
# your code to generate plot 
dev.off()
```

then load image with

.[LABEL](PATH/NAME.png) or with

```{r echo=FALSE, out.width='100%', ...}
knitr::include_graphics('PATH/NAME.png')
```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM