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

1

7

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.

Handoff answered 7/8, 2018 at 15:49 Comment(1)
After answering this question, I realised in was a possible duplicate of R Markdown HTML Number Figures. However, the answer lacked any decent answers which used bookdown so I have added a similar answer to this other post.Saker
S
7

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")
```
Saker answered 7/8, 2018 at 16:24 Comment(2)
Awesome thanks Mikey. I realized that fig.cap doesn't work with tables. Is there a tbl.cap?Handoff
Also helpful: #64896814Kowatch

© 2022 - 2024 — McMap. All rights reserved.