Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot animation in knitr rmarkdown

Problem:

Hi, I try to make an animated plot in a rmarkdown document. Here is my code:

```{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)
```

The loop work fine, and passed into a function, I'am able to save it in several formats with 'saveLatex', 'saveHTML' or 'saveVideo'. However, when 'knit' the .Rmd file in order to obtain a PDF, the animation does not appear, there is just this line written:

video of chunk lmSim

If I knit it in HTML, only the play button of the video is displayed. However, If I open the HTML in my browser (firefox) it is displayed correctly.

There is no error message displayed. I'm using R version 3.2.0, the latest R Studio version, 1.10.5 knitr version on a MacBook Pro Yosemite. I didn't find any relevant information or documentation to solve my problem.

Questions:

So, is it simply possible to have an embeded animation into a PDF generated with rmarkdown/knitr ?

Do I have to install another program to deal with videos in PDF (I have ffmpeg on my computer)?

Many thanks!

Thanks Yihui! It works very well with the following settings (reading the PDF with Adobe):

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

```{r lmSim, fig.show='animate', out.width = '6in'}
like image 711
user2523409 Avatar asked May 27 '15 07:05

user2523409


1 Answers

Have you tried with ggplot and gganimation? For example:

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

See that you need to save first your animation. You need to have establish your work directory.

After you can call it from the chat or html in markdown (not from the R chuck) like:

![your caption here](your_animation.gif)
like image 172
RRuiz Avatar answered Sep 23 '22 07:09

RRuiz