Search code examples
rr-markdownknitrgganimate

How to render a gganimate graph in html using rmarkdown::render(), without generating unwanted output


I am trying to render gganimate() plots in html using an r-markdown document. I am able to create the html document (though the simple example below takes at least a minute) and the gganimate graphic successfully loads in the browser (firefox), however, I get a bunch of unwanted output in the browser.

The unwanted output looks like this:


Frame 1 (1%)

Frame 2 (2%)

Frame 3 (3%)

...

Frame 96 (96%)

Frame 97 (97%)

Frame 98 (98%)

Frame 99 (99%)

Frame 100 (100%)

Finalizing encoding... done!


Like I said, after this unwanted output, the animation is indeed displayed correctly.

I have tried messing around with the knitR code-chunk heading options. Mostly been looking at these options here: https://bookdown.org/yihui/rmarkdown/r-code.html

I have also tried the solutions suggested on this post: suppress console output in r markdown, but keep plot Specifically, I have tried wrapping the ggplot object in "invisible".

Just copy the code below into an Rmarkdown document, save this Rmarkdown document as "example.Rmd", then, in the R console run: rmarkdown::render("example.Rmd")

---
    title: "Testing gganimate with R Markdown"
    output: html_document
---

```{r message = FALSE}
library(ggplot2)
library(gganimate)
ggplot(mtcars, aes(factor(cyl), mpg)) + 
  geom_boxplot() + 
  # Here comes the gganimate code
  transition_states(
    gear,
    transition_length = 2,
    state_length = 1
  ) +
  enter_fade() + 
  exit_shrink() +
  ease_aes('sine-in-out')
```

Solution

  • One workaround for this is to assign the animation to an object goo <- ggplot(... and write the animation to a file anim_save("goo.gif", goo) while suppressing results from the code chunk results = FALSE. Then render the gif in markdown immediately after the code chunk ![](goo.gif).

    E.g.

    ---
    title: "Testing gganimate with R Markdown"
    output: html_document
    ---
    
    
    ```{r message = FALSE, warning = FALSE, results = FALSE}
    library(ggplot2)
    library(gganimate)
    goo <- ggplot(mtcars, aes(factor(cyl), mpg)) + 
      geom_boxplot() + 
      # Here comes the gganimate code
      transition_states(
        gear,
        transition_length = 2,
        state_length = 1
      ) +
      enter_fade() + 
      exit_shrink() +
      ease_aes('sine-in-out')
    
    anim_save("goo.gif", goo)
    ```
    
    
    ![](goo.gif)