Search code examples
rr-markdownknitrpandocbookdown

RMarkdown: Space in LaTeX output at place of code for float


When including code for a figure between two paragraphs in RMarkdown, the float resulting from the code might be placed at a different place of the document, leaving space between the paragraphs in the LaTeX/PDF output file.

The following minimal example illustrates the issue:

---
output: pdf_document
---

This is my first paragraph. 
Next in the Rmd file would be the code for the figure.  
The figure is correctly treated as a float by LaTeX, meaning that LaTeX will put it to the next suitable position.
```{r pressure, echo=FALSE, fig.cap="Example", out.width='0.5\\textwidth', fig.pos='B'}
  plot(pressure)
```
The problem now is, that this leaves space to my second paragraph.
Usually, this should not be the case.
In pure LaTeX, there is a linebreak, of course, but no vertical space in addition.

Solution

  • If you put \vspace{-\parsep} at the start of the following text, you'll get the line break without the extra space. That is,

    ---
    output: pdf_document
    ---
    
    This is my first paragraph. 
    Next in the Rmd file would be the code for the figure. 
    The figure is correctly treated as a float by LaTeX, meaning that LaTeX will put it to the next suitable position.
    ```{r pressure, echo=FALSE, fig.cap="Example", out.width='0.5\\textwidth', fig.pos='B'}
      plot(pressure)
    ```
    \vspace{-\parsep}The problem is now fixed.
    

    I don't see any other way to do this: knitr puts blank lines around the figure environment when it generates the LaTeX.