R Markdown cite figure before figure inserted

Viewed 61

New to Markdown so trying to navigate. I'm using bookdown. I'm trying to work out how to insert an image and but cite it prior to the code.

What I'd like:

Blablabla (Figure 1). Blablabla bla.

FIGURE.

Caption: Figure 1.

I'm currently doing:

![Cholesterol Metabolism](figure/cholesterol metabolism.png)
```{r}
fig_nums <- captioner() 
fig_nums("Cholesterol Metabolism", "CAPTION FOR FIG 1")
```

And to cross reference the figure I have

(r fig_nums("Cholesterol Metabolism", display = "cite"))

But how can I cross reference before the figure?

Am I also right in thinking that this method will let me insert figures throughout and it will automatically change the number as I go along? So, say I place a figure before the existing Figure 1, it will re-number that figure to Figure 2.

Thank you!

1 Answers

It's recommended to include images using knitr::include_graphics() in a code chunk like this:

```{r tiger, fig.cap = "A giant tiger"}
knitr::include_graphics(tiger.png)
```

Note that for cross-referencing to work you need to equip the chunk with a name (here tiger) and set a caption using fig.cap.

You can reference the figure as follows (no matter whether before or after the chunk):

Figure \@ref(fig:tiger) shows a tiger.

[This](#fig:tiger) is a tiger. (HTML output only)

Note that it might be necessary to build the book for the references to work.

enter image description here

(image from here)

And yes, bookdown ensures that multiple images are numbered correctly.

Related