I am trying to make an animated plot in R from a large data set (from a cyclic scientific experiment) in order to visualize the change of two variables over time. I use the animation library simply:
saveGIF( for(i in 1:100){ mygraph(i) }, interval = 0.1, ani.width = 640, ani.height = 480)
where mygraph(i) just displays the graph for cycle i. If I use plot() to create a graph, then it works fine, but if I use ggplot instead (which I would like to do, because I ultimately want to use it to create more complex graphs), then it does not work and I get the following conclusion:
Executing: 'convert' -loop 0 -delay 'animation.gif' convert: InvalidArgument `-delay': animation.gif @ error/convert.c/ConvertImageCommand/1161. an error occurred in the conversion... see Notes in ?im.convert [1] FALSE
I am very new to R, so I got a little stuck and I did not develop a solution looking at ?im.convert or search. Any suggestions would be greatly appreciated ...
Example with dummy data as requested:
library(animation) library(ggplot2) x <- 1:20 y <- 21:40 z <- c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4) data <- data.frame(x,y,z) mygraph <- function(i) { plot(data$x[data$z == i], data$y[data$z == i], title(title)) } saveGIF( for(i in 1:4){ title <- paste("Cycle", i, sep=" ") mygraph(i) }, interval = 0.5, ani.width = 640, ani.height = 480)
This works, but if the function mygraph is mygraph :
mygraph <- function(i) { ggplot() + geom_point(aes(x=data$x[data$z == i], y=data$x[data$z == i])) }
... then it gives me an error as stated above.