Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't generate \label{fig:mwe-plot} with knitr

I am having trouble generating \label{} for plots when using knitr to go from a *.Rmd file to a *.md file via knitr; and then converting to *.pdf via pandoc.

An MWE for my *.Rmdis included below:

```{r Setup, include=FALSE, results="hide", warning=FALSE}
opts_chunk$set(dev="cairo_pdf", fig.lp="fig:", echo=FALSE, results="hide", 
               message=FALSE, warning=FALSE)
```

```{r mwe-plot, fig.cap = "MWE plot."}
library(ggplot2)
ggplot(mtcars, aes(factor(cyl))) +
  geom_bar() 
```

I knit:

knit("mwe.Rmd") 

Then I use pandoc

pandoc -o mwe.pdf mwe.md 

I should be able to cross-reference the plot with Figure \ref{fig:mwe-plot} in my *.Rmd source. But it seems that the \label{fig:mwe-plot} hasn't been created in mwe.tex if I run:

pandoc -o mwe.pdf mwe.md

Thank you!

like image 615
Tom Avatar asked Jun 06 '14 16:06

Tom


1 Answers

The issue is that you are writing a R markdown file and the options related to LaTeX don't work (they have no effect) in such documents. fig.cap works, but fig.lp won't and you won't get any \label{} added at all because the output hook for Rmd documents is markdown and in general there is no label etc there.

In this case you need to write the \label{} manually in fig.cap as if you were adding this explicitly in a LaTeX document. For example:

```{r mwe-plot, fig.cap = "\\label{fig:mwe-plot}MWE plot."}
library(ggplot2)
ggplot(mtcars, aes(factor(cyl))) +
  geom_bar()
```

Now knitr will dump that caption verbatim into the markdown file using the markdown image markup conventions (we need to escape the backslash when entering the string in R, hence the \\ in the fig.cap argument). Pandoc will then be able to work with this caption and the label and the references to it should all resolve themselves.

The other option is more complicated; there is nothing stopping you from writing your own custom hooks to do this for you, but you'll have to study the LaTeX hook and the MD hook to see how to combine elements of both that you need.

Note that this issue (chunk options that pertain to LaTeX outputs) applies to all such chunk options when writing an Rmd file. This is sort of implied in the Options page of the KNitr website but it still caught me by surprise when I first started using Knitr with markdown and using pandoc to render.

like image 184
Gavin Simpson Avatar answered Sep 27 '22 22:09

Gavin Simpson