Search code examples
ranimationgif

saveGIF() returns empty GIF


In R I am trying to get an animated GIF based on several images. I wrote a function returning the images and use the saveGIF() function of the animation package to create the GIF. The function returning the images works (I see the images popping up in the Viewer). When using saveGIF a GIF is created, there is no error message but the GIF is empty.

 library(leaflet)
 library(mapview)
 library(animation)

  latitude = c(seq(48.13608, 52.48608, 0.00145))
  longitude = c(seq(11.57278, 13.40278, 0.00061))

  sampledf <- as.data.frame(cbind(longitude, latitude))


  plot.1 <- function(df)
  {
  for (i in seq(1,nrow(df),300)){
  m<- leaflet() %>%
  addTiles() %>%
  setView( lng = 12.48778
           , lat = 50.31108
           , zoom = 4 )    %>%

  addPolylines(data = df[1:i,],
               lng = ~longitude,
               lat = ~latitude,
               color = ~"red")

  print(m)
 }
 }

  saveGIF(plot.1(sampledf),movie.name="test.gif", interval=0.5, ani.width=1980/2, ani.height=1080/2)

Solution

  • This might be a convoluted way to approach but I could do this by first creating png files for the sampledf data and then used magick library for producing gif's.

    library(leaflet)
    library(mapview)
    library(magick)
    
    counter <- 1 
    for (i in seq(1,nrow(sampledf),300)){
    
        m <- leaflet() %>%
              addTiles() %>%
              setView( lng = 12.48778
                     , lat = 50.31108
                     , zoom = 4 )    %>%
               addPolylines(data = sampledf[1:i,],
                            lng = ~longitude,
                            lat = ~latitude,
                            color = ~"red")
    
         mapshot(m, file = paste0("plot_", counter, ".png"))
         counter = counter + 1
    }
    file_names <- list.files(pattern = "plot_\\d+.png$", full.names = TRUE)
    
    image_read(file_names) %>%
       image_animate(fps = 1) %>%
       image_write("output.gif")
    

    enter image description here