Animate plots using echarts4r when quarto slides are on-screen
Asked Answered
M

1

6

I am making a Revealjs presentation using Quarto in R Studio. I am using the package {echarts4r} to make my plots. {echarts4r} comes with default animations. When I render the presentation the default animation has already loaded for all the slides.

I want to run the default echarts4r animations when the slide is active (i.e. when the slide is in view) and reset when some other slide is in view. Could someone help me with this?

Here is the code for the quarto presentation.

---
title: "A Title"
subtitle: "A Subtitle"
author: "First Last"
institute: "Some Institute"
date: today
self-contained: true
format: revealjs
---


## Introduction

Hello There!


## Pie Chart

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

data <- tibble(name = c("A", "B", "C", "D", "E", "F", "G"),
             number = c(9.7, 2.1, 2.1, 1.9, 1.9, 1.9, 80.4))

data %>% 
e_charts(name) %>% 
e_pie(number, radius = c("50%", "70%")) %>% 
e_legend(orient = "vertical", right = "5", top = "65%")
```
Ministrant answered 9/10, 2022 at 20:29 Comment(1)
Note that this is not an echarts4r-related problem. The animation of highcharter plots is already done when we arrive on the slide.Bunyan
S
2

This isn't a fix or a Quarto method. However, this workaround is dynamic. I worked out what needs to happen with both echarts4r and highcharter because of the comment by @bretauv.

Assign Element IDs

The only thing you'll change with your charts is that you need to give them an element ID. IDs need to be unique across the entire presentation. It's perfectly okay to use something like 'ec0', 'ec1'... and so on for your plots' ids. (You only need to do this to plots that animate.)

Here's an example.

```{r pltEchart, echo=F} 

iris |> group_by(Species) |> 
  e_charts(Sepal.Length, elementId = "pltEcht") |>  # <--- id is here
  e_scatter(Sepal.Width) 

```

For highcharter, and most other widget style packages, adding the element id isn't built in. Here's how you add the id for highcharter.

```{r penquins,echo=F}

hc <- hchart(penguins, "scatter", 
             hcaes(x = flipper_length_mm, y = bill_length_mm, group = species))

hc$elementId <- "hc_id"

hc

```

Re-Animating Plots

For each of echarts4r plots, to apply this next part you need the slide it's on and it's element id.

For highcharter, you also need to know the order in which it appears in your presentation (only in terms of other highcharter plots).

Whether you use the less dynamic approach or the more dynamic approach, what remains is adding a JS chunk to your QMD. This chunk can go anywhere in the script file. (I usually put any JS in my RMDs/QMDs at the end.)

If you were not aware, JS is built-in. You don't need to do anything new or different to use JS this way. However, if you were to run this chunk in the source pane, it won't do anything. You have to render it to see it in action. If you end up changing the JS or writing more of your own, don't assume what you see in RStudio's viewer or presentation pane is exactly what you'll see in your browser.

I would skim over what you have to change for both methods before you decide! If you're not comfortable using JS, the second is definitely your best bet.

Customized Information For Each Presentation For Each Re-Animated Plot

For each plot you re-animate, you'll have to identify:

  1. a substring of the slide title OR the slide number (where slide numbers are included on the slides via YAML declaration)
  2. plot element ids
  3. plot order (plot order or sequence is for Highcharts only).

For the slide title substring, as you use it in the JS:

  • it's a substring of the title based on the hash or anchor that is assigned in the background
  • substring is all lowercase
  • no special characters
  • must be unique to that slide

If you're unsure what to use or how to find what's unique—there's an easy way to find that information. If you open your presentation in your browser from the presentation pane in RStudio, the URL of the slides will look similar to this.

Every slide will have the same initial component to the URL, http://localhost:7287/#/, but beyond that, every slide will be unique.

http://localhost:7287/#/another-hc

The string after the # is the title anchor for that slide. You can use exactly what's in the URL (after #/).

Put it Altogether

This continuously checks if the slide has changed (10-millisecond interval). If there's a slide change, it then checks to see if one of the three plots is on that slide. If so, the slide animation is restarted.

What you need to personalize in the JS

ecReloader for charts4r has 2 arguments:

  1. title substring OR slide number
  2. plot element ID

hcReloader for highcharter has 3 arguments:

  1. title substring OR slide number
  2. plot element ID
  3. plot sequence number

In the setInterval function (chunk named customizeMe, you will need to write a function call for each plot you want to re-animate. In my example, I reanimated three plots. This is the ONLY part you modify. (Note that each line needs to end with a semi-colon.)

  ecReloader('code', 'pltEcht');        /* slide title. plot element id */
  hcReloader('highchart', 'hc_id', 0);  /* slide title, id, sequence */
  hcReloader(6, 'another_hc_id', 1);    /* slide number, id, sequence */

     /* assuming only one on slide */
setInterval(function() { 
  var current = window.location.hash;
  tellMe = keepLooking(current);
  if(tellMe) {                        /* if the slide changed, then look */
  ecReloader('code', 'pltEcht');
  hcReloader('highchart', 'hc_id', 0);
  hcReloader(6, 'another_hc_id', 1);    /* second highcharter plot */
  }
}, 10); // check every 10 milliseconds

In your presentation, you need to take both of the JS chunks to make this work. (Chunk names are customizeMe and reloaders.)

I'm sure there's a way to customize the appearance of the slide numbers; this code is based on the default, though.

Here's all the JS to make this work.


```{r customizeMe,echo=F,engine='js'}

     /* assuming only one on slide */
setInterval(function() { 
  var current = window.location.hash;
  tellMe = keepLooking(current);
  if(tellMe) {                        /* if the slide changed, then look */
  ecReloader('code', 'pltEcht');
  hcReloader('highchart', 'hc_id', 0);
  hcReloader(6, 'another_hc_id', 1);    /* second highcharter plot */
  }
}, 10); // check every 10 milliseconds

```
    
```{r reloaders,echo=F,engine='js'}

// more dynamic; a couple of key words for each plot

// multiple options for addressing Echarts plots
function ecReloader(slide, id) {
  /* slide (string)  slide title unique substring (check URL when on the slide)
                --or-- 
           (integer) as in the slide number
     id (string)     element id of the plot to change */
  if(typeof slide === 'number') {                        // slide number provided
    which = document.querySelector('div.slide-number');  // page numbers like '6 / 10'
    validator = Number(which.innerText.split(' ')[0]);
    if(slide === validator) {                            // slide number matches current slide
      var ec = document.getElementById(id);
      ele = echarts.init(ec, get_e_charts_opts(ec.id));
      thatsIt = get_e_charts_opts(ec.id);          /* store data */
      ele.setOption({xAxis: {}, yAxis: {}}, true); /* remove data */
      ele.setOption(thatsIt, false);               /* append original data */
    }
  } else {                                               // unique element in slide title 
    if(window.location.hash.indexOf(slide) > -1) {
      var ec = document.getElementById(id);
      ele = echarts.init(ec, get_e_charts_opts(ec.id));
      thatsIt = get_e_charts_opts(ec.id);          /* store data */
      ele.setOption({xAxis: {}, yAxis: {}}, true); /* remove data */
      ele.setOption(thatsIt, false);               /* append original data */
    }
  }
}

// multiple options for addressing Highcharts plots, assumes 1 chart per slide!
function hcReloader(slide, id, order) {
  /* slide (string)  slide title unique substring (check URL when on the slide)
                --or-- 
           (integer) as in the slide number
     id (string)     element id of the plot to change
     order (integer) 0 through the number of charts in the plot, which one is this plot?
                  (in order of appearance) */
  if(typeof slide === 'number') {                        // slide number provided
    which = document.querySelector('div.slide-number');  // page numbers like '6 / 10'
    validator = Number(which.innerText.split(' ')[0]);
    if(slide === validator) {                            // slide number matches current slide
      var hc1 = document.getElementById(id).firstChild;  
      Highcharts.chart(hc1, Highcharts.charts[order].options); // re-draw plot
    }
  } else {                                               // unique element in slide title
    if(window.location.hash.indexOf(slide) > -1) {
      var hc1 = document.getElementById(id).firstChild;
      Highcharts.chart(hc1, Highcharts.charts[order].options); // re-draw plot
    }
  }
}

/* Current Slide Section (bookmark #) */
oHash = window.location.hash;

/* check if the slide has changed */
function keepLooking (nHash) { 
  if(oHash === nHash) {
    return false;
  } else {
    oHash = nHash;          /* if slide changed, reset the value of oHash */
    return true;
  }
}

```

Here is the entire QMD script I used to create and test this so you can see how it works.


---
title: "Untitled"
format: 
  revealjs:
    slide-number: true
editor: source
---

## Quarto

```{r basics, echo=F}
library(echarts4r)
library(tidyverse)
library(htmltools)
library(highcharter)

```

```{r data, include=F,echo=F}

data("iris")
data(penguins, package = "palmerpenguins") 

```

word

## Bullets

more words

## More Plots; How about Highcharter?

```{r penquins,echo=F}

hc <- hchart(penguins, "scatter", 
             hcaes(x = flipper_length_mm, y = bill_length_mm, group = species))

hc$elementId <- "hc_id"

hc

```

## Code

`echarts` style plot

```{r pltEcht, echo=F} 

iris |> group_by(Species) |> 
  e_charts(Sepal.Length, elementId = "pltEcht") |> e_scatter(Sepal.Width) 

```


## Another HC

```{r penquins2,echo=F}

hc2 <- hchart(iris, "scatter",
              hcaes(x = Sepal.Length, y = Sepal.Width, group = Species))

hc2$elementId <- "another_hc_id"

hc2

```


```{r customizeMe,echo=F,engine='js'}

     /* assuming only one on slide */
setInterval(function() { 
  var current = window.location.hash;
  tellMe = keepLooking(current);
  if(tellMe) {                        /* if the slide changed, then look */
  ecReloader('code', 'pltEcht');
  hcReloader('highchart', 'hc_id', 0);
  hcReloader(6, 'another_hc_id', 1);    /* second highcharter plot */
  }
}, 10); // check every 10 milliseconds

```

```{r reloaders,echo=F,engine='js'}

// more dynamic; a couple of key words for each plot

// multiple options for addressing Echarts plots
function ecReloader(slide, id) {
  /* slide (string)  slide title unique substring (check URL when on the slide)
                --or-- 
           (integer) as in the slide number
     id (string)     element id of the plot to change */
  if(typeof slide === 'number') {                        // slide number provided
    which = document.querySelector('div.slide-number');  // page numbers like '6 / 10'
    validator = Number(which.innerText.split(' ')[0]);
    if(slide === validator) {                            // slide number matches current slide
      var ec = document.getElementById(id);
      ele = echarts.init(ec, get_e_charts_opts(ec.id));
      thatsIt = get_e_charts_opts(ec.id);          /* store data */
      ele.setOption({xAxis: {}, yAxis: {}}, true); /* remove data */
      ele.setOption(thatsIt, false);               /* append original data */
    }
  } else {                                               // unique element in slide title 
    if(window.location.hash.indexOf(slide) > -1) {
      var ec = document.getElementById(id);
      ele = echarts.init(ec, get_e_charts_opts(ec.id));
      thatsIt = get_e_charts_opts(ec.id);          /* store data */
      ele.setOption({xAxis: {}, yAxis: {}}, true); /* remove data */
      ele.setOption(thatsIt, false);               /* append original data */
    }
  }
}

// multiple options for addressing Highcharts plots, assumes 1 chart per slide!
function hcReloader(slide, id, order) {
  /* slide (string)  slide title unique substring (check URL when on the slide)
                --or-- 
           (integer) as in the slide number
     id (string)     element id of the plot to change
     order (integer) 0 through the number of charts in the plot, which one is this plot?
                  (in order of appearance) */
  if(typeof slide === 'number') {                        // slide number provided
    which = document.querySelector('div.slide-number');  // page numbers like '6 / 10'
    validator = Number(which.innerText.split(' ')[0]);
    if(slide === validator) {                            // slide number matches current slide
      var hc1 = document.getElementById(id).firstChild;  
      Highcharts.chart(hc1, Highcharts.charts[order].options); // re-draw plot
    }
  } else {                                               // unique element in slide title
    if(window.location.hash.indexOf(slide) > -1) {
      var hc1 = document.getElementById(id).firstChild;
      Highcharts.chart(hc1, Highcharts.charts[order].options); // re-draw plot
    }
  }
}

/* Current Slide Section (bookmark #) */
oHash = window.location.hash;

/* check if the slide has changed */
function keepLooking (nHash) { 
  if(oHash === nHash) {
    return false;
  } else {
    oHash = nHash;          /* if slide changed, reset the value of oHash */
    return true;
  }
}

```  

You can put the JS anywhere in your QMD.

If you see delays in loading (flashing, that sort of thing), you can lower the milliseconds between intervals. (That number is at the end of the setInterval function, where you see }, 10).

If something goes wrong, you can just set the JS to eval=F. You didn't actually change anything in your presentation permanently.

Sidedress answered 16/12, 2022 at 18:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.