R: "InvalidArgument` -delay" with animation and ggplot

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.

+5
source share
1 answer

This works if you end ggplot in a print() statement, for example.

 mygraph <- function(i) { g <- ggplot() + geom_point(aes(x=data$x[data$z == i], y=data$x[data$z == i])) print(g) } 

This is a variation of R-FAQ 7.22, Why does graphic / trellis not work?

+5
source

Source: https://habr.com/ru/post/1214474/


All Articles