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)```
I'm not aware of such an option for pandoc
to set the floating option of figures when converting a Markdown document to LaTeX. If you choose Markdown for its simplicity, you should not expect too much power from it, even with powerful tools like pandoc
. Bottom line: Markdown is not LaTeX. It was designed for HTML instead of LaTeX.
Two ways to go:
use the Rnw syntax (R + LaTeX) instead of Rmd (R Markdown) (examples); then you will be able to use the chunk option
fig.pos='H'
after you\usepackage{float}
in the preamble; in this case, you have full power of LaTeX, and pandoc will not be involvedhack at the LaTeX document generated by pandoc, e.g. something like
library(knitr)knit('foo.Rmd') # gives foo.mdpandoc('foo.md', format='latex') # gives foo.texx = readLines('foo.tex')# insert the float packagex = sub('(\\\\begin\\{document\\})', '\\\\usepackage{float}\n\\1', x)# add the H option for all figuresx = gsub('(\\\\begin\\{figure\\})', '\\1[H]', x)# write the processed tex file backwriteLines(x, 'foo.tex')# compile to pdftools::texi2pdf('foo.tex') # gives foo.pdf
If you do not like these solutions, consider requesting a new feature to pandoc on Github, then sit back and wait.
I am using KnitR and markdown in RSTUDIO, the solution for my case is adding in the preamble \usepackage{float}
:
---title: "Proyect 2"author: "FV"date: "2016-12-3"output: pdf_document: fig_caption: yes fig_crop: no fig_height: 2 fig_width: 3 highlight: haddock keep_tex: yes number_sections: yes toc: yes toc_depth: 2 html_document: fig_caption: yes theme: journal toc: yes toc_depth: 2header-includes: - \usepackage{graphicx}- \usepackage{float}---
And then adding this lines of code (fig.pos='H') in the very first lines:
```{r echo=FALSE,warning=FALSE} library(knitr) opts_chunk$set(fig.path='figure/graphics-', cache.path='cache/graphics-', fig.align='center', external=TRUE, echo=TRUE, warning=FALSE, fig.pos='H' ) a4width<- 8.3 a4height<- 11.7```