Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a figure caption in Rmarkdown?

I am thinking about writing my thesis with rmarkdown and latex. I'm getting the hang of how it all works, however, when I try to add a figure (not an R plot) to the text and render it to pdf, the caption and in-text reference dissappear.

This is the code snippet I use to add a figure:

---
title: "Untitled"
output: pdf_document
---

see figure \ref{fig1}.

![picture \label{fig1}](figure1.png)

This is what knitr creates:

This is what pandoc creates:

Question: How do I make figure captions and in-text references to those figures in Rmarkdown that will display when rendered to pdf?

OR

How do I tell pandoc what Rmarkdown is so it will render R code and plots?

like image 575
rosannavh Avatar asked Jun 26 '15 03:06

rosannavh


People also ask

How do I add a figure in Rmarkdown?

To add an image in markdown you must stop text editing, and you do this with the command [Alt text] precedeed by a ! Then you have to add the path to the image in brackets. The path to the image is the path from your directory to the image.


2 Answers

Please see the documentation of R Markdown for PDF output, and in particular, look for fig_caption. Figure captions are turned off by default in R Markdown, and you have to turn them on (fig_caption: true). You can also find this setting from the gear button on the toolbar of RStudio IDE.

like image 132
Yihui Xie Avatar answered Oct 18 '22 18:10

Yihui Xie


Update: please check https://github.com/yihui/knitr/issues/1063.

Question: How do I make figure captions and in-text references to those figures in Rmarkdown that will display when rendered to pdf?

To get the cross-reference in the PDF produce by LaTeX you need to run LaTeX more than once. Some LaTeX IDE does it for you.

knitr is only running LaTeX once and that is the reason that you only get ??. To confirm that this was the problem I ran

library(knitr)
knitr()

in R that returned

see figure \ref{fig1}.

\begin{figure}[htbp]
\centering
\includegraphics{imagem.jpg}
\caption{picture \label{fig1}}
\end{figure}

which is a valid LaTeX code.

How do I tell pandoc what Rmarkdown is so it will render R code and plots?

Pandoc only understand Markdown (not RMarkdown). First you have to call knitr to generate the Markdown from the RMarkdown and after it call Pandoc to convert the Markdown to LaTeX.

like image 32
Raniere Silva Avatar answered Oct 18 '22 20:10

Raniere Silva