Rmarkdown with html, how to reference figures?
Asked Answered
T

1

7

Using RMarkdown I always generate pdf documents via Rmd -> pandoc -> TeX -> pdflatex -> pdf and accomplish figure references using \\label{something} in the fig.cap as in the follow example:

---
title: "Foo"
author: "Mark Andrews"
date: "10 January 2019"
output: pdf_document
---

See Figure \ref{figfoo} and see Figure \ref{figbar}. 

```{r fig1, fig.cap='A figure\\label{figfoo}'}
plot(rnorm(10))
```


```{r fig2, fig.cap='Another figure\\label{figbar}'}
plot(rnorm(10))
```

If I change output: pdf_document to output: html_document, that does not work, understandably because it is relying on LaTeX's cross referencing system.

So how do Figure references work with html_document in RMarkdown?

The following does not work:

---
title: "Foo"
author: "Mark Andrews"
date: "10 January 2019"
output: html_document
---

See Figure \@ref(fig:fig1) and see Figure \@ref(fig:fig2). 

```{r fig1, fig.cap='A figure}'}
plot(rnorm(10))
```


```{r fig2, fig.cap='Another figure'}
plot(rnorm(10))
```

But the following does work:

---
title: "Foo"
author: "Mark Andrews"
date: "10 January 2019"
output: bookdown::html_document2
---

See Figure \@ref(fig:fig1) and see Figure \@ref(fig:fig2). 

```{r fig1, fig.cap='A figure}'}
plot(rnorm(10))
```


```{r fig2, fig.cap='Another figure'}
plot(rnorm(10))
```

Does that mean that the only way to cross-reference figures when producing html from Rmarkdown is to use output: bookdown::html_document2. That's fine, if so, but am I missing something?

Tent answered 10/1, 2019 at 20:2 Comment(2)
Possible duplicate of cross-reference to figure in R Markdown with html output is not workingParochial
The answer is yes. That is the only portable way that I'm aware of.Chufa
T
4

Having heard from Yihui Xie, I think we can take it for granted that yes, the only way to do figure cross references in html_document in rmarkdown is to do

---
output: bookdown::html_document2
---

in the header.

Tent answered 10/1, 2019 at 23:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.