【问题标题】:Plot animation in knitr rmarkdown在 knitr rmarkdown 中绘制动画
【发布时间】:2015-08-09 03:56:55
【问题描述】:

问题:

您好,我尝试在 rmarkdown 文档中制作动画图。这是我的代码:

```{r lmSim, fig.show='animate'}
library(animation)
library(plyr)

oopt = ani.options(interval = 0.3, nmax = 101)

a <- sort(rnorm(100, 2))
b <- sort(rnorm(100, 7))
out <- vector("list", 101)
for (i in 1:ani.options("nmax")) {
  ji <- seq(from = 0, to = 5, by = .05)
  a <- jitter(a, factor = 1, amount = ji[i])
  fab1 <- lm(a ~ b)
  coe <- summary(fab1)$coefficients
  r2 <- summary(fab1)$r.squared
  if (coe[2, 4] < .0001) p <- " < .0001"
  if (coe[2, 4] < .001 & coe[2, 4] > .0001) p <- " < .001"
  if (coe[2, 4] > .01) p <- round(coe[2, 4], 3)
  plot(a ~ b, main = "Linear model")
  abline(fab1, col = "red", lw = 2)
  text(x = min(b) + 2, y = max(a) - 1, 
       labels = paste("t = ", round(coe[2, 3], 3), ", p = ", p, ", R2 = ", round(r2, 3)))
  out[[i]] <- c(coe[2, 3], coe[2, 4], r2)
  ani.pause()
  }

ani.options(oopt)
```

循环工作正常,并传递到一个函数中,我可以使用“saveLatex”、“saveHTML”或“saveVideo”将其保存为多种格式。但是,当“编织” .Rmd 文件以获取 PDF 时,动画不会出现,只写了这行:

video of chunk lmSim

如果我用 HTML 编织它,则只显示视频的播放按钮。但是,如果我在浏览器 (firefox) 中打开 HTML,它会正确显示。

没有显示错误消息。我在 MacBook Pro Yosemite 上使用 R 版本 3.2.0、最新的 R Studio 版本、1.10.5 knitr 版本。我没有找到任何相关信息或文档来解决我的问题。

问题:

那么,是否可以简单地将动画嵌入到使用 rmarkdown/knitr 生成的 PDF 中?

我是否必须安装另一个程序来处理 PDF 格式的视频(我的电脑上有 ffmpeg)?

非常感谢!

谢谢一辉!它适用于以下设置(使用 Adob​​e 阅读 PDF):

---
title: "Sim"
author: ""
header-includes:
   - \usepackage{animate}
...
---

```{r lmSim, fig.show='animate', out.width = '6in'}

【问题讨论】:

  • 如果您想要的唯一输出格式是 PDF,也许您可​​以尝试使用块选项 out.width = ''。请注意,您必须在标题中包含\usepackage{animate} (rmarkdown.rstudio.com/pdf_document_format.html),并且还必须使用 Acrobat Reader 来查看 PDF。如果可行,我将在答案中进行解释。

标签: r knitr r-markdown


【解决方案1】:

你尝试过 ggplot 和 gganimation 吗?例如:

library(gapminder)
library(gganimate)
library(ggplot)

head(gapminder)
theme_set(theme_bw())

p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = 1, color = continent, frame = year)) +
  geom_point() +
  scale_x_log10()


animation<-gganimate(p, "your_animation.gif")#Or to your path

请注意,您需要先保存动画。你需要建立你的工作目录。

在你可以从聊天或 Markdown 中的 html 调用它之后(不是从 R 夹头),比如:

![your caption here](your_animation.gif)

【讨论】:

    【解决方案2】:

    这个答案可能为时已晚,但希望能对其他人有所帮助。我建议将 R 代码作为单独的文件保存并运行在同一目录中,并且只将动画导入为 gif 以减少演示中的延迟。这在 ioslides 中对我有用:

    ## Time series visualization
    
    ![time series](myanimation.gif){width=80%}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多