rpaneldynamically-generatedquartoecharts4r

Echarts4r in programmatically created tabsets in quarto not rendering?


Taking the example in this How to programmatically generate tabset-panel in quarto?, I have established rendering charts in dynamically rendered tabsets.

I am hoping to replace the ggplots with interactive echarts, which work independently of the quarto document.

See below code:

---
title: "Panel tabs"
format:
  html:
    embed-resources: true
    
---

```{r echo=F, warning=F, message=F}
library(tidyverse)
library(echarts4r)

data <- iris

species <- list()

for(i in unique(data$Species)){
  
  species[[paste(i)]] <- data %>%
    filter(Species == i) %>%
    e_charts(Sepal.Length)  %>%
    e_line(Sepal.Width)
  
  
  # species[[paste(i)]] <- data %>%
  #   filter(Species == i) %>%
  #   ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
  #   geom_point() +
  #   theme_bw(base_size = 18)
  #   
  # 
  # 
  # species[[paste(i)]] <- data %>%
  #   filter(Species == i) %>%
  #   plotly::plot_ly(x = ~ Sepal.Length, y = ~ Sepal.Width)
  
  
  
}

```

# Iris Plots 

::: {.panel-tabset}


```{r}
#| results: asis
#| fig-width: 14
#| fig-height: 6

iwalk(species, ~ {
  cat('## ', .y, '\n\n')
  
  print(.x)
  
  cat('\n\n')
  
})

```
:::

This quarto document in rendered via a download handler on a shiny app, but either rendering this way or directly through the qmd does not work.

I've commented out the ggplot2 code which works. When I try to render echarts4r, the code either doesn't render at all or returns the html composition of the Echart. I suspect this is related to the cat() functionality, but cannot find a solution (or whether there is one). Any thoughts would be much appreciated!


Solution

  • Since you are generating the output asis, you need the underlying HTML code for the E-charts. print method for htmltools::tagList()) will help you in this regard. And also you need to make sure all the JS dependencies of E-charts are loaded and hence you need a dummy E-chart graph.

    ---
    title: "Panel tabs"
    format:
      html:
        embed-resources: true
    ---
    
    ```{r}
    #| echo: false
    #| warning: false
    #| message: false
    
    library(tidyverse)
    library(echarts4r)
    
    data <- iris
    
    species <- list()
    
    for(i in unique(data$Species)) {
      species[[paste(i)]] <- data %>%
        filter(Species == i) %>%
        e_charts(Sepal.Length)  %>%
        e_line(Sepal.Width)
    }
    
    ```
    
    # Iris Plots 
    
    ```{r}
    #| include: false
    
    # This is a dummy chart, just to make sure all E-charts' 
    # JS dependency are loaded.
    e_chart()
    ```
    
    ::: {.panel-tabset}
    
    ```{r}
    #| results: asis
    
    iwalk(species, ~ {
      cat('## ', .y, '\n\n')
      print(htmltools::tagList(.x))
      cat('\n\n')
    })
    
    ```
    :::