'Using plot() to make basic animations

You can use the plot function in R repeatedly to make basic animations. Example:

x <- seq(0, 0.99, by=0.01)
y <- 4*x*(1 - x)
x <- seq(0, 4.99, by=0.01)
y <- rep(y, 5)
y <- y*exp(-0.05*x)

# animate
for (i in 1:length(x)) {
  plot(x[i], y[i], xlim=c(0, 5), ylim=c(0, 1))
}

However, if you try to add lines or other features or multiple plots, the lines flicker at best or do not show up during animation at worst. (At least in Rgui. I haven't tested this in Rstudio)

for (i in 1:length(x)) {
  plot(x[i], y[i], xlim=c(0, 5), ylim=c(0, 1))
  lines(x[1:i], y[1:i], col=2)
}

for (i in 1:length(x)) {
  par(mfrow=c(1, 2))
  plot(x[i], y[i], xlim=c(0, 5), ylim=c(0, 1))
  plot(x[i], y[i], xlim=c(0, 5), ylim=c(0, 1), pch=20)
}

The plot seems to be refreshed only at the end of each loop, so adding a delay through Sys.sleep() doesn't work. I guess what I'm after is the plot equivalent of flush.console().

for (i in 1:length(x)) {
  plot(x[i], y[i], xlim=c(0, 5), ylim=c(0, 1))
  lines(x[:1:i], y[1:i], col=2)
  Sys.sleep(0.1)
}

I know it is possible to achieve this sort of thing through ggplot, but I was hoping for a non-ggplot answer because I understand R's base plotting functionalities well, whereas ggplot is still a mystery to me.

If the animation looks completely fine to you

You might have a better computer than me. Try this code instead:

for (i in 1:length(x)) {
  Sys.sleep(0.02)
  plot(x[i], y[i], xlim=c(0, 5), ylim=c(0, 1))
  Sys.sleep(0.02)
  lines(x[1:i], y[1:i], col=2)
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source