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.