Search code examples
r-markdownmarkdownquarto

using a for loop to generate a series of plots in new powerpoint slides using quarto


I am creating a quarto powerpoint presentation and want to use a dataset to iterate over all the classes in a variable and do a plot for each class on a new slide. However, my plot doesn't seem to show up

---
title: "test_quarto_presentation"
format: pptx
editor: visual
---

## Quarto

Trying to iterate over each species and print the distributions on slides

```{r}
library(tidyverse)
```

```{r, results='asis'}
for (species in unique(iris$Species)){
  cat(paste0('## ', species))
  print("test")
  
  print(iris %>%
           filter(Species == "virginica") %>%
           ggplot(aes(x = Petal.Length)) +
           geom_histogram())}
```

Solution

  • Here is an option by producing the plots beforehand using purrr based on this discussion:

    ---
    title: "test_quarto_presentation"
    format: pptx
    ---
    
    ```{r, include=FALSE}
    library(tidyverse)
    spec_name <- unique(iris$Species)
    
    make_hist <- function(spec) {
     iris |> 
               filter(Species == spec) |> 
               ggplot(aes(x = Petal.Length)) +
               geom_histogram()
    }
    list_hist <- map(spec_name, make_hist)
    
    df <- tibble(spec = spec_name, plots = list_hist)
    ```
    
    
    
    ```{r}
    #| output: asis
    res <- pmap_chr(df, \(spec, plots) {
      knitr::knit_child(text = c(
        "## `r spec`",
        "```{r}",
        "#| echo: false",
        "plots",
        "```",
        ""), envir = environment(), quiet = TRUE)
    })
    cat(res, sep = '\n')
    ```
    

    Output:

    enter image description here