Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rmarkdown with html, how to reference figures?

Tags:

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?

like image 469
mjandrews Avatar asked Jan 10 '19 20:01

mjandrews


People also ask

How do you reference an equation in r markdown?

1 Number and reference equations. You may refer to it using \@ref(eq:binom) , e.g., see Equation (2.1). Equation labels must start with the prefix eq: in bookdown. All labels in bookdown must only contain alphanumeric characters, : , - , and/or / .

How do I embed a plot in r markdown?

You can embed an R code chunk like this: ```{r} summary(cars) ``` You can also embed plots, for example: ```{r, echo=FALSE} plot(cars) ``` Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

How do you show results in RMarkdown?

To produce a complete report containing all text, code, and results, click “Knit” or press Cmd/Ctrl + Shift + K. You can also do this programmatically with rmarkdown::render("1-example. Rmd") . This will display the report in the viewer pane, and create a self-contained HTML file that you can share with others.


1 Answers

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.

like image 54
mjandrews Avatar answered Dec 18 '22 17:12

mjandrews