首页 > 解决方案 > 如何使用 R Markdown 在 html 输出中创建动画

问题描述

这是我尝试过的事情的清单。

---
title: "test_gif"
output: html_document
---


``` {r, animation.hook='gifski', dev='png', interval=0.2}
library(gganimate)
ggplot(airquality, aes(Day, Temp, group = Month)) + 
  geom_line() + 
  transition_reveal(Month)
```

错误:从第 8-12 行退出 (test_gif.Rmd) hook_animation(options)(x, options) 中的错误:要使用 hook_gifski(),代码块必须生成“png”图像而不是“gif”。调用: ... hook_plot -> hook_plot_md_base -> hook_plot_html -> 执行停止

尽管我使用了这里提到的 dev = 'png' https://yihui.name/en/2018/08/gifski-knitr/,但我无法使其工作。

然后我尝试使用 FFmpeg 渲染器

---
title: "test_gif"
output: html_document
---


```{r, animation.hook='ffmpeg', interval=0.2}
library(gganimate)
ggplot(airquality, aes(Day, Temp, group = Month)) + 
  geom_line() + 
  transition_reveal(Month) -> p
animate(p)
```

0 libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100 test_gif_files/figure-html/unnamed-chunk-1-%d.gif:没有这样的文件或目录|.. ..................................................... .............| 100%无R代码的普通文本

输出文件:test_gif.knit.md

/usr/local/bin/pandoc +RTS -K512m -RTS test_gif.utf8.md --to html4 --from markdown+autolink_bare_uris+tex_math_single_backslash+smart --output test_gif.html --email-obfuscation none --self-contained --standalone --section-divs --template /Library/Frameworks/R.framework/Versions/3.5/Resources/library/rmarkdown/rmd/h/default.html --no-highlight --variable highlightjs=1 --变量'主题:引导程序'--include-in-header /var/folders/pv/cs874rmn7dj9n08xdyc7s3nm0000gn/T//RtmpOqkC3V/rmarkdown-str28173033d049.html --mathjax --variable 'mathjax-url: https://mathjax.rstudio .com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' --lua-filter /Library/Frameworks/R.framework/Versions/3.5/Resources/library/rmarkdown/rmd/lua/pagebreak.lua --lua-filter /Library/Frameworks/R.framework/Versions/3.5/ Resources/library/rmarkdown/rmd/lua/latex-div.lua File test_gif_files/figure-html/unnamed-chunk-1.webm not found in resource path Error: pandoc document conversion failed with error 99 执行停止

然后我按照这个方法,使用 gifski::save_gif 保存 gif,然后使用 include_graphics 在后续块中显示。 https://community.rstudio.com/t/make-an-rstudio-notebook-inline-animation-that-loops-with-gganimate/27489/2

---
title: "test_gif"
output: html_document
---


```{r}
library(gganimate)
library(gifski)
ggplot(airquality, aes(Day, Temp, group = Month)) + 
  geom_line() + 
  transition_reveal(Month) -> p
animate(p)
```

```{r, animation.hook='gifski', interval = 0.2}
p
```

错误(相同):从第 18-19 行退出 (test_gif.Rmd) hook_animation(options)(x, options) 中的错误:要使用 hook_gifski(),代码块必须生成“png”图像而不是“gif”。调用: ... hook_plot -> hook_plot_md_base -> hook_plot_html -> 执行停止

我的最终目标是在最终的 html 文档中创建动画,而不会在中间生成任何临时文件。即使有任何其他替代方法可以完成这项工作,我也会很高兴。

标签: rr-markdownknitrgganimate

解决方案


使用gganimate包,您无需设置 chunk 选项animation.hook。这就够了:

```{r, dev='png', interval=0.2}
library(gganimate)
ggplot(airquality, aes(Day, Temp, group = Month)) + 
  geom_line() + 
  transition_reveal(Month)
```

推荐阅读