How to keep figure captions in R Markdown when fig

2019-09-01 03:59发布

问题:

I'm having trouble with figure captions in html documents generated using R Markdown. If I don't specify the fig.retina option, or if I set it to 1, the output document has a figure caption. If I set it to a value that isn't 1, however, the future caption is missing but the text for it is present as the alt text for the figure. How can I keep the figure captions?

An example:

---
title: "Example"
output:
  html_document:
    fig_caption: yes
    fig_retina: 2
---


Text text text

```{r fig.cap="Figure 1. Some random numbers"}
plot(rnorm(25),runif(25)) 
```

Renders to give a document with no figure caption, but if I change the value for fig.retina to 1 I get a figure caption. The same thing happens if I set fig.retina in the chunk rather than globally.

回答1:

Here is the relevant documentation

#' @param fig_retina Scaling to perform for retina displays (defaults to 2 when
#'   \code{fig_caption} is \code{FALSE}, which currently works for all widely
#'   used retina displays). Set to \code{NULL} to prevent retina scaling. Note
#'   that this will always be \code{NULL} when \code{keep_md} is specified (this
#'   is because \code{fig_retina} relies on outputting HTML directly into the
#'   markdown document).
#' @param fig_caption \code{TRUE} to render figures with captions

So if you don't specify the default will be 2. I did find that if I changed your code to

---
title: "Example"
output:
  html_document:
    fig_caption: yes

---


Text text text

```{r fig.cap="Figure 1. Some random numbers"}
plot(rnorm(25),runif(25)) 
```

It showed the caption.

update

After looking around a bit I found this

Note the chunk option fig.retina=1: without it, rmarkdown::render() will generate plots for Retina displays, which means the plots are written in raw <img> tags instead of ![](), and Pandoc will not be able to generate figure captions in that case.

So probably you need to just use normal markdown for adding html for the caption.