rggplot2quarto

Failing to automate slide creation for each plot (pptx format, R)


I have a list with 100 plots which I want to automate via quarto such that each plot is produced in a new slide of a power point presentation. I am using Quarto 1.4.555 with R 4.4.0 via RStudio 2024.4.2.764

Here is a reproducible example of what I did:

---
title: "test-auto"
format: pptx
---

```{r setup, include=FALSE}
library(knitr)
library(tidyverse)
```

```{r load-data}
plot_list_q <-  list(
  ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point(),
  ggplot(mtcars, aes(x = hp, y = drat)) + geom_point()
)

```

```{r function}
# Slide creation function
create_slide <- function(plot, index) {
  knit_expand(text = c(
    paste("## Plot", index),
    "",
    "```{r}",
    "plot_list_q[[{{index}}]]",
    "```"
  ))
}
```

```{r generate}
#| echo: false
#| results: asis

# Generate all slides
slides <- map2(plot_list_q, seq_along(plot_list_q), create_slide)
cat(unlist(slides), sep = "\n")
```

There are indeed two plot slides, but the plot is not generated: enter image description here


Solution

  • I think the problem lies within knit_expand which does not evaluate the code within the same environment and the variable substitution is not correct. Hence I would try to use knit_child():

      create_slide <- function(plot, index) {
        knitr::knit_child(text = c(
          paste("## Plot", index),
          "",
          "```{r}",
          "plot_list_q[[", index, "]]",
          "```"
        ), envir = environment(), quiet = TRUE)
      }
    

    enter image description here

    BTW: you could use map2_chr, than you would not need the unlist in the cat function.