Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-Numbering of Figure and Table Captions for HTML Output in R Markdown

Is there a way to automatically number the figures in captions when I knit R Markdown document into an HTML format?

What I would like is for my output to be the following:

Figure 1: Here is my caption for this amazing graph.

However, I am currently getting the following:

Here is my caption for this amazing graph.

Here is my MWE:

---
title: "My title"
author: "Me"
output: 
  html_document:
  number_sections: TRUE
  fig_caption: TRUE
---

```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```

```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```

```{r table1, fig.cap="Here is my caption for an amazing table."}
head(mtcars, 2)
```

I have read that this issue is resolved with Bookdown but I've read the Definitive Guide to Bookdown, cover to cover, and can't find it.

like image 272
DuckDuckGoose Avatar asked Aug 07 '18 15:08

DuckDuckGoose


1 Answers

If you wish to have numbered figures, you will need to use an output format provided by bookdown. These include html_document2, pdf_document2 etc. See here for a more comprehensive list of options.

Changing your document example html_document to bookdown::html_document2 will resolve your problem.

---
title: "My title"
author: "Me"
output: 
  bookdown::html_document2:
  number_sections: TRUE
  fig_caption: TRUE
---

```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```

```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```

```{r plot2, fig.cap="Here is my caption for another amazing graph."}
plot(y,x)
```

If you want to label tables created by knitr::kable, you will need to specify the caption within the table call itself

```{r table1}
knitr::kable(mtcars[1:5, 1:5], caption = "Here is an amazing table")
```
like image 90
Michael Harper Avatar answered Oct 31 '22 16:10

Michael Harper