Does anyone know how to number the figures in the captions, for HTML format R Markdown script?
For PDF documents, the caption will say something like:
Figure X: Some Caption Text
However, the equivalent caption for the HTML version will simply say:
Some Caption Text
This makes cross-referencing figures by number completely useless.
Here is a minimal example:
---
title: "My Title"
author: "Me"
output:
pdf_document: default
html_document: default
---
```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```
```{r cars2, fig.cap = "Another amazing plot"}
plot(cars)
```
I have tried setting toc
, fig_caption
and number_sections
within each of the output formats, but this does not seem to change the result.
The other answers provided are relatively out of date, and this has since been made very easy using the bookdown package. This package provides a number of improvements which includes the built-in numbering of figures across Word, HTML and PDF.
To be able to use bookdown, you need to first install the package install.packages("bookdown")
and then use one of the output formats. For HTML, this is html_document2
. Taking your example:
---
title: "My Title"
author: "Me"
date: "1/1/2016"
output: bookdown::html_document2
---
```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```
```{r cars2, fig.cap = "Another amazing plot"}
plot(cars)
```
These Figures will be numbered Figure 1
and Figure 2
. Providing the code chunk is named and has a caption, we can cross reference the output using the the syntax \@ref(fig:foo)
where foo
is the name of the chunk i.e. \@ref(fig-cars)
. You can learn more about this behaviour here
Further Reading
- R Markdown: The definitive Guide: Chapter 11 provides a great overview of bookdown
- Authoring books with bookdown provides a comprehensive guide on bookdown, and recommended for more advanced details.