chase171
chase171

Reputation: 51

Cross reference and caption not working in Rmd file

Can anyone help me understand how to write my header so that the figure caption and cross reference works?

I am practicing making captions and cross references to a simple plot in my Rmd file. I understand that to do so, I should add to my header: "output: bookend::pdf_document2" and "fig_caption = yes". Then, to a chunk called myfigure, I should add "fig.cap = "\label{fig:myfigure} My caption". To cross reference this figure I should write in the text "@ref(fig:myfigure)". My code is below. It won't knit because the formatting of the header is wrong.

---
title: "knit"
author: "Chase Hommeyer"
date: "4/1/2019"
output: bookdown::pdf_document2
  toc: true
  fig_caption: yes
---

```{r myfigure, fig.cap = "\\label{fig:myfigure} My caption"}
plot(pressure)
```

My plot is called \@ref(fig:myfigure).

Then, I tried deleting the whitespace before toc and fig_caption, and it knit, but no caption appeared, and the text literally printed "@ref(fig:myfigure)" instead of a cross reference. The header I tried is here:

---
title: "knit"
author: "Chase Hommeyer"
date: "4/1/2019"
output: bookdown::pdf_document2
toc: true
fig_caption: yes
---

I also tried adding "pdf_document:" to the header, but the same issue of no caption and the cross reference being literally "@ref(fig:myfigure)". This header I tried is here:

 ---
title: "knit"
author: "Chase Hommeyer"
date: "4/1/2019"
output: bookdown::pdf_document2
  pdf_document:
    toc: true
    fig_caption: yes
---

Can anyone help me understand how to write my header so that it works?

Upvotes: 4

Views: 3653

Answers (2)

Jhou
Jhou

Reputation: 31

use \ref{fig:myfigure} instead of \\@ref(fig:myfigure)

See RStudio Community Post

Upvotes: 3

J_F
J_F

Reputation: 10372

You have a wrong YAML header and some wrong understanding of referencing. I used this RMD file:

---
title: "knit"
author: "Chase Hommeyer"
date: "4/1/2019"
output: 
  bookdown::pdf_document2:
    toc: true
    fig_caption: yes
---

```{r myfigure, fig.cap = "My caption"}
plot(pressure)
```

My plot is called Figure \@ref(fig:myfigure).

First, break the line after output in the header. The whitespaces are very important in the YAML header!

Then, read the bookdown manual:

The label of a figure environment is generated from the label of the code chunk, e.g., if the chunk label is foo, the figure label will be fig:foo (the prefix fig: is added before foo). To reference a figure, use the syntax, where label is the figure label, e.g., fig:foo.

To reference your plot with the chunk name "myfigure", just write \@ref(fig:myfigure). The caption of the figure can be set via fig.cap in the chunk options.

Upvotes: 2

Related Questions