creating gif in r
I'm trying to create a GIF of the plot below:
x<-NULL
y<-NULL
for(i in 1:500){
y[i]<-sum(rnorm(i))/i
x[i]<-i
plot(y~x, type="l")
abline(y=0)
Sys.sleep(0.25)
}
4
Author: Márcio Mocellin, 2018-05-02
1 answers
There are several ways to produce a GIF in R. If you want to transform images into gif right on your computer, you will need imageMagick.
I show here an example using the package magick
and the functions image_graph()
to save each graphic in an object, image_animate()
for the animation and image_write()
to save the gif.
Saving the plot of each interaction with the function image_graph()
:
library(magick)
# atenção que pode demorar alguns minutos
x<-1
y<-1
for(i in 1:250){
y[i]<-sum(rnorm(i))/i
x[i]<-i
name <- paste0('fig', i)
assign(name, image_graph(res = 65))
plot(y~x, type="l")
dev.off()
}
Now that each plot is saved in a different object (figi
), we can join all in one vector:
# vetor de nomes
figs <- paste0('fig', 1:250)
# unindo os plots
img <- mget(figs)
img <- image_join(img)
Creating and saving gif:
gif <- image_animate(img, fps = 10, dispose = "previous")
image_write(gif, "gif.gif")
Reference for more features of the magick
package can be found here .
EDIT :
Depending on the amount and complexity of the figures created, it is important to remember the available memory:
# remover todos os plots da memória
rm(list = ls()[ls() %in% paste0('fig', 1:250)])
7
Author: Willian Vieira, 2018-05-03 10:19:31