How to make a figure caption in Rmarkdown?

前端 未结 3 814
余生分开走
余生分开走 2021-02-02 17:28

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 re

相关标签:
3条回答
  • 2021-02-02 17:42

    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.

    0 讨论(0)
  • 2021-02-02 17:45

    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.

    0 讨论(0)
  • 2021-02-02 17:53

    I just found a very useful solution here.

    First, include the following chunk:

    ```{r functions, include=FALSE}
    # A function for captioning and referencing images
    fig <- local({
        i <- 0
        ref <- list()
        list(
            cap=function(refName, text) {
                i <<- i + 1
                ref[[refName]] <<- i
                paste("Figure ", i, ": ", text, sep="")
            },
            ref=function(refName) {
                ref[[refName]]
            })
    })
    ``` 
    

    After, we can add the caption of the figure/table in the figure chunk options like:

    ```{r, fig.cap=paste("Your caption.")}
    
    • See that fig.cap works better with paste.
    0 讨论(0)
提交回复
热议问题