Site icon R-bloggers

Animation basics for a vacation

[This article was first published on R snippets, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Since I have a vacation this time I decided to implement some entertaining graphics. I have chosen to animate a Cassini oval.
The task is can be accomplished using polar equation:
The implementation of the animation is given by the following code:

library(animation)< o:p>

xy <- function(angle, a, b) {< o:p>
  ca <- cos(2 * angle)< o:p>
  r2 <- a ^ 2 * ca + sqrt(a ^ 4 * ca ^ 2 (a ^ 4 b ^ 4))< o:p>
  c(sqrt(r2) * cos(angle), sqrt(r2) * sin(angle))< o:p>
}< o:p>

go <- function() {< o:p>
  angle <- seq(0, 2 * pi, len = 1000)< o:p>
  par(mar = rep(0,4))< o:p>
  b <- 1 + 0.5 * seq(0, 1, len = 31) ^ 3< o:p>
  b <- c(b, 1.5, rev(b))< o:p>
  for (i in b) {< o:p>
    coord <- t(sapply(angle, xy, a = 1, b = i))< o:p>
    plot(coord, type = “l”, < o:p>
      xlim = c(-2, 2), ylim = c(-1.25, 1.25))< o:p>
    polygon(coord, col = “gray”)< o:p>
  }< o:p>
}< o:p>

ani.options(interval = 0.1)< o:p>
saveGIF(go())< o:p>

Parameter a is fixed to 1 and b changes from 1 to 1.5. In order to achieve smooth animation the sequence defining changes of b is not uniform but is more dense near 1.

And here is the result:


To leave a comment for the author, please follow the link and comment on their blog: R snippets.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.