Home > Software engineering >  Insert Pagebreak for Output after Code Chunk
Insert Pagebreak for Output after Code Chunk

Time:11-26

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!

CodePudding user response:

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.

```{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')

CodePudding user response:

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 has the value "yes", the output of that chunk will be in 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(is.null(options$next_page)) {
      default_source_hook(x, options)
    } else if (options$next_page == "yes")  {
      paste0(default_source_hook(x, options),
        "\n\n\\newpage\n\n")
    } else {
      default_source_hook(x, options)
    }
  }
)
```


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

chunk output in the next page


  • Related