4

I want to insert an image in a R Markdown report, so i used this:

![Uniform Crossover](C:\Users\Miguel Prada\OneDrive\Documentos\Estudio\Invest UPM\ProjectANN\reports\crossover.png)

This works, but the image is located in the top of the page, not in the place where i wrote the code. Does anyone know why this is happening? Thanks

mapra99
  • 43
  • 1
  • 1
  • 4
  • are you rendering to html, pdf or word? – Richard Telford Jul 29 '18 at 16:37
  • Hi Richard. I am knitting it to Pdf – mapra99 Jul 29 '18 at 16:41
  • 1
    Try `knitr::include_graphics` + use `fig.xxx` chunk option https://yihui.name/knitr/options/#plots – Tung Jul 29 '18 at 16:43
  • 2
    If you look up other discussions on how LaTeX deals with figure/picture/table placement, you'll see that it has its idea of what is best, defaulting to the top of the page following the paragraph to which it is "anchored". There are ways to override this, and perhaps `knitr`'s `fig.pos` can help, where you encourage LaTeX's optimization engine to bias in different directions. So, since you're producing PDFs, expand your learning to understand its use of `\begin{figure}[fig.pos]`. – r2evans Jul 29 '18 at 23:28
  • Gentlement, thanks for your helpful answers. It worked – mapra99 Jul 30 '18 at 01:02

2 Answers2

5

As of 2019, perhaps the best solution is to make a Latex preamble for your Rmd file as explained here. In other words:

Save following preamble.tex file in your working directory:

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

Note that the "H" tells the image to go where you insert it. Then call for the preamble.tex in the YAML header of your Rmd file:

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

![Uniform Crossover](C:\Users\Miguel Prada\OneDrive\Documentos\Estudio\Invest UPM\ProjectANN\reports\crossover.png)
Mikko
  • 7,530
  • 8
  • 55
  • 92
0

Reply from comments

From @tung

Try knitr::include_graphics + use fig.xxx chunk option and see more in options/#plots

From @r2evans

If you look up other discussions on how LaTeX deals with figure/picture/table placement, you'll see that it has its idea of what is best, defaulting to the top of the page following the paragraph to which it is "anchored".

There are ways to override this, and perhaps knitr's can help, where you encourage LaTeX's optimization engine to bias in different directions. So, since you're producing PDFs, expand your learning to understand its use of \begin{figure}[fig.pos].

Nicolás Alarcón Rapela
  • 2,714
  • 1
  • 18
  • 29