I'm trying to create a GIF from 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)
}
I'm trying to create a GIF from 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)
}
There are several ways to produce a gif in R. If you want to transform the images into gif directly on your computer, you will need imageMagick .
Here's an example using the magick
package and the image_graph()
to save each graphic to an object, image_animate()
to animation and image_write()
to save the gif.
Saving the plot of each interaction with the image_graph()
function:
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 to a different object ( figi
), we can join all into a 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 quantity and complexity of the created figures, it is important to remember the available memory:
# remover todos os plots da memória
rm(list = ls()[ls() %in% paste0('fig', 1:250)])