davidgohel / ggiraph

make 'ggplot' graphics interactive
https://davidgohel.github.io/ggiraph
772 stars 73 forks source link

Quarto `#| panel: tabset` works with `ggplot2`, not with `ggiraph::girafe()` #303

Open sda030 opened 1 month ago

sda030 commented 1 month ago

Quarto has a #| panel: tabset chunk option that is a very nifty shorthand way of producing multiple plots in tabs, without having to split up each chunk (which does work). This shorthand way works with ggplot, but not with ggiraph. Any idea for a workaround?

# Works

```{r}
#| panel: tabset
#| output: asis
library(ggplot2)
plots <-
purrr::map(unique(mtcars$cyl), ~{
  ggplot(mtcars[mtcars$cyl == .x, ], aes(x=mpg, y=hp)) +
  geom_point()
})
names(plots) <- as.character(unique(mtcars$cyl))
for(i in names(plots)) {
  cat(sprintf("## Cyl: %s\n", i))
  print(plots[[i]])
  cat(sprintf("\n\n"))
}

ggiraph works for single plot

ggiraph::girafe(ggobj = plots[[1]])

Does not work with multiple plots (there is not even any intermediate md-output that I could fiddle to work)

#| panel: tabset
#| output: asis # Have also tried without this
library(ggiraph)
for(i in names(plots)) {
  cat(sprintf("## Cyl: %s\n", i))
  ggiraph::girafe(ggobj=plots[[i]]) # Have also tried with print outside
  cat(sprintf("\n\n"))
}


Expected: 
![image](https://github.com/user-attachments/assets/992bfc81-7286-432d-afab-fc23ca363b59)
davidgohel commented 1 month ago

hello @sda030 I doubt output: asis manage and collect htmldependancies as it is done via a classical print method.

This https://ardata-fr.github.io/flextable-book/rendering.html#looping-in-r-mardown-documents may help. See also the original documentation https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html

PS : I am sorry, I can't spend time on that for now and provide you a tested solution :(

sda030 commented 1 month ago

Oh, David, I would buy you a basket of assorted cheeses, croissants and wine, this simplified things a lot.

For anyone else wondering, it's as simple as this:

```{r}
#| panel: tabset
#| output: asis 
data <- mtcars
lapply(unique(mtcars$cyl), function(x) {
  knitr::knit_child(text = c(
    '## Cyl: `r x`',
    '',
    '```{r}',
    'library(ggplot2)',
   'library(ggiraph)',
   'girafe(ggobj=',
   'ggplot(data[data$cyl == x, ], aes(x=mpg, y=hp, tooltip=mpg)) +',
    'geom_point_interactive()',
    ')',
    '```',
    ''
  ), envir = environment(), quiet = TRUE)
}) |> unlist() |> cat(sep = '\n')
davidgohel commented 1 month ago

:)

Note that this is not so much a cliché about me (with the exception of wine, which I avoid drinking during the week).