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

后端 未结 1 1450
后悔当初
后悔当初 2021-01-04 13: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

相关标签:
1条回答
  • 2021-01-04 13:56

    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.

    0 讨论(0)
提交回复
热议问题