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

雨燕双飞 提交于 2019-12-30 08:17:10

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/24086498/i-cant-generate-labelfigmwe-plot-with-knitr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!