2
votes

I struggle with a blank page problem in my knited PDF R markdown document. It appears that when I plot 2 ggplot() graphs in a single code chunk, a blank page is created before rendering the graphs. Here is an example of the problem (complete .Rmd file, uncomment beginning and ending of each chunk to run, where UNCOMMENT stands!):

---
title: "Test"
author: "My Name"
output:
  pdf_document:
    number_sections: yes
    toc: yes
---

\newpage

# Plots

## First subtitle

Here I plot some data:

#UNCOMMENT```{r pressure, echo=FALSE, message = FALSE}
library(tidyverse)

# line chart
ggplot(pressure, aes(x = temperature, y = pressure)) +
        geom_line()

# step chart
ggplot(pressure, aes(x = temperature, y = pressure)) +
        geom_step()

#UNCOMMENT```

\newpage

# More plots

#UNCOMMENT```{r, echo = FALSE}

# line chart with points
ggplot(pressure, aes(x = temperature, y = pressure)) +
        geom_line() +
        geom_point()

# line chart
ggplot(pressure, aes(x = temperature, y = pressure)) +
        geom_line()

#UNCOMMENT```


When knited, the PDF output has a blank page before my "More plots" chunk, i.e. 4th page is blank:

[![pdf output][1]][1] PDF output

Any idea why it happens and how to solve that issue? If I separate the 2 plots in 2 different chunks the problem is solved but I want to plot multiple graphs in some chunks so it's not a solution.

Thanks in advance!

1

1 Answers

2
votes

Giving credit to this link. using the captions helps center the plots. This is just a suggestion not an explicit answer to your question.

---
 title: "Test"
 author: "My Name"
 output: pdf_document
 header-includes:
   - \usepackage{subfig}
---  

```{r echo =FALSE, results=FALSE}
captions <- c("Caption 1",
              "Caption 2", 
              "Caption 3",
              "Caption 4")
```

```{r, echo=FALSE, cache=FALSE, results=FALSE, warning=FALSE,  comment=FALSE, message= FALSE, eval =T,  fig.cap =    "Overall Caption", fig.subcap=captions, out.width='.49\\linewidth', fig.asp=1, fig.ncol = 2}
library(ggplot2)
 # line chart
 p1<- ggplot(pressure, aes(x = temperature, y = pressure)) +
         geom_line()

 # step chart
 p2<-ggplot(pressure, aes(x = temperature, y = pressure)) +
         geom_step()


 # line chart with points
 p3<-ggplot(pressure, aes(x = temperature, y = pressure)) +
         geom_line() +
         geom_point()

 # line chart
 p4<-ggplot(pressure, aes(x = temperature, y = pressure)) +
         geom_line()


 p1
 p2
 p3
 p4
 ```