Figure position in markdown when converting to PDF with knitr and pandoc

I present an alternative solution. Instead of inserting [H] symbols into a latex document in a post-hoc manner, I suggest redefining the figure environment to ignore any position arguments and use [H].

To do this, create a .tex file in the same directory as the .Rmd file which redefines the figure environment, and update the YAML header in the .Rmd to include the file during compilation.

Here is an example of a .tex file:

\usepackage{float}
\let\origfigure\figure
\let\endorigfigure\endfigure
\renewenvironment{figure}[1][2] {
    \expandafter\origfigure\expandafter[H]
} {
    \endorigfigure
}

Here is example .Rmd which includes it (assuming you called the .tex file ‘preamble-latex.tex’):

---
title: "example"
author: "you"
date: "`r format(Sys.time(), '%d %B %Y')`"
output:
  rmarkdown::pdf_document:
    fig_caption: yes        
    includes:  
      in_header: preamble-latex.tex
---

```{r, fig.cap='Markdownvellous!'}
plot(1:10, 1:10)
```

Leave a Comment