rggplot2ggiraph

Interactive ggiraph objects created in a loop does not show in quarto HTML output


I am trying to create a loop that generates +100 interactive graphs using the ggiraph package. The plots appear as expected when I run the loop interactively. However, when I render the .qmd document, the interactive graphs are not showing.

A reproducible example, including the YAML header, is below.

Can you make the interactive graphs in the last loop appear in the rendered output? Thanks.

---
title: "test"
format: html
---

```{r}
library(dplyr)
library(ggplot2)
library(ggiraph)
set.seed(1)
tmp_names <- diamonds %>% select(where(is.double)) %>% names() %>% sample(2)
```

## These not-interactive plots appear:
## When I run the chunk in the session and when the .qmd document is rendered
```{r}    
for(i in tmp_names){
  tmp_plot <- diamonds %>%
    select(all_of(i)) %>% 
    ggplot(aes(x = .data[[i]]))+
    geom_density()
  
  print(tmp_plot)
}
```

## These interactive plots only appear when I run the loop in a session,
## Not when the .qmd file is rendered.
```{r}
for(i in tmp_names){
  tmp_plot <- diamonds %>%
    select(all_of(i)) %>% 
    ggplot(aes(x = .data[[i]],
               tooltip = "I'm interactive!"))+
    geom_density_interactive()
  
   print(girafe(ggobj = tmp_plot))
  }
```

Solution

  • Looping over html widgets in Quarto/R Markdown doesn't work in the standard way as static plots do. One solution is to store your ggiraph objects in a list and use htmltools::tagList():

    ---
    title: "test"
    format: html
    ---
    
    ```{r}
    library(dplyr)
    library(ggplot2)
    library(ggiraph)
    set.seed(1)
    tmp_names <- diamonds %>% select(where(is.double)) %>% names() %>% sample(2)
    ```
    
    ```{r}
    #| results: asis
    #| echo: false
    gg_list <- list()
    for(i in tmp_names){
      tmp_plot <- diamonds %>%
        select(all_of(i)) %>% 
        ggplot(aes(x = .data[[i]],
                   tooltip = "I'm interactive!"))+
        geom_density_interactive()
      
      gg_list[[i]] = girafe(ggobj = tmp_plot)
    }
    ```
    
    ```{r}
    htmltools::tagList(gg_list)
    ```
    
    

    I would suggest checking out the solutions linked from the GitHub issue on this topic: https://github.com/davidgohel/ggiraph/issues/55