Quarto “forgets” ggplot theme

Here’s something that vexed me for a while: Quarto would “forget” the ggplot theme set and use the default style when updating a figure.

Description: In Rstudio, I have a Quarto document set up (possibly also applies to Rmarkdown). Caching is turned on with the execute: cache: true as follows:

---
title: "My Document"
format: html
execute:
cache: true
---

Near the beginning, I set the ggplot theme to be used, like this:

library(ggplot2)
theme_set(theme_classic())

Expected behaviour: the theme is applied to all figures.

Observed behaviour: the theme is applied to all figures, but when I subsequently edit one of the figures, it comes up in the default theme, ignoring the theme I set globally.

Solution: One way to resolve this is to delete the cache (those *_cache and *_files folders), and have Quarto rebuild the document from scratch. But this kind of defeats the purpose of caching.

Solution: move that library(ggplot2); theme_set(theme_classic()) part into a separate block, and use cache: false on that block, like this:

```{r}
#| cache: false
library(ggplot2)
theme_set(theme_classic())
```

Why does this work properly? Because setting the theme is no longer hidden in the cache. This means hat when I update that figure, Rstudio will run that bit setting the theme, and the (modified) code for the figure. When running the code of the figure, the theme is set.

I guess, alternatively, I could set the theme in each plot, but that’d mean repeating myself and would make changing the theme more complicated…

Published 8 December 2023