creation of gif in r

Asked

Viewed 579 times

4

I’m trying to create a Plot GIF 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)
}

1 answer

7


There are several ways to produce a gif on R. If you want to transform gif images right on your computer, you will need to imagemagick.

I show here an example using the package magick and the functions image_graph() to save each graph to 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 gather 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 the gif:

    gif <- image_animate(img, fps = 10, dispose = "previous")

    image_write(gif, "gif.gif")

Reference for more features of the package magick can be found here.

EDIT:

Depending on the number 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)])
  • Thanks @Willian . But: Error in axis(side = side, at = at, labels = labels, ...) : &#xA; Magick: unable to extend cache '#FFFFFFFFFFFF': Não há espaço disponível no dispositivo @ error/cache.c/OpenPixelCache/3883

  • 1

    Probably a memory problem due to very large files. One option is to decrease the number of charts to turn into gif or reduce the quality of the chart (with the res). Also, you can see if there is a bug in your code. You can try debugging by going step by step and measuring the size of the objects with the feature object.size().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.