Skip to content

Instantly share code, notes, and snippets.

@marvinschmitt
Last active April 29, 2024 11:07
Show Gist options
  • Save marvinschmitt/f912f239f5b36551785adadb775a2f7a to your computer and use it in GitHub Desktop.
Save marvinschmitt/f912f239f5b36551785adadb775a2f7a to your computer and use it in GitHub Desktop.
---
title: "Dynamic label demo"
author: "Marvin Schmitt"
engine: knitr
---
## Standard
![A very important plot.](https://picsum.photos/400/200.jpg){#fig-1}
![A second very important plot.](https://picsum.photos/400/150.jpg){#fig-2}
Here's a reference to @fig-1, and here is @fig-2.
## Dynamic label
We can construct the figure label in `R` with `paste(...)`, then use inline code execution and `I()` to pass the verbatim text to Quarto:
```
`{{r}} I(paste("@fig-", fig_index, sep=""))`
```
```{r}
fig_index = 1
```
This is `{r} I(paste("@fig-", fig_index, sep=""))`.
```{r}
fig_index = 2
```
This is `{r} I(paste("@fig-", fig_index, sep=""))`.
## Dynamic label in figure as well
Here we define the label dynamically:
```{r}
fig_index = 157
```
![Still a very important plot.](https://picsum.photos/300/150.jpg){`{r} I(paste("#fig-", fig_index, sep=""))`}
... and another one to make sure we change the `fig_index` variable value a bit.
```{r}
fig_index = 246
```
![Very important indeed.](https://picsum.photos/400/100.jpg){`{r} I(paste("#fig-", fig_index, sep=""))`}
Now we reference the first dynamically labeled figure dynamically:
```{r}
fig_index = 157
```
This is `{r} I(paste("@fig-", fig_index, sep=""))`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment