8.6 Animations

The gifski package can assemble a set of sequential plots into a GIF image, and thus an animation.

  1. Install the gifski package.
  2. Insert a R chunk. Add animation.hook=gifski in the chunk option.
  3. Set the time interval between frames, e.g., interval=0.25.
  4. Set cache=TRUE to speed up the processing time.
```{r, animation.hook="gifski", interval=0.25, cache=TRUE} 
```
  1. Add a set of sequential plots into the R chunk through a for-loop.
# Define the function f(x)=sin(x)/x
f <- function(x){
  return(sin(x) / x)
}

# Animation created from a for-loop
for (n in 1:20) {
  plot(1:n, f(1:n), 
       pch=16,            # Use a filled dot for each point
       xlim = c(0,21),    # The range of the x-axis
       ylim = c(-1, 1),   # The range of the y-axis
       main = 'Sequence', # Title
       xlab = 'x',        # x label
       ylab = 'sin(x)/x'  # y label
  )
}