ranimationimage-processing

How do I create a GIF from multiple PNGs in R?


I developed a code to create an animated track on a world map. Which I first save as a .png and would then like to turn into a .gif file.

I downloaded the ImageMagick and tried what was suggested here: Creating a Movie from a Series of Plots in R but can't get it to work. Could someone help me?

This is my library:

library(purrr)
library(magick)
library(ggplot2)
library(animation)
library(png)
library(caTools) # for write.gif  

my dataframe are coordinates, so something like this:

            x       y
    1   100.3   13.4
    2   101.3   13.3
    3   101.4   13.2
    4   101.4   13.0
    5   102.4   12.9
    6   102.4   12.7
    7   103.5   12.5
    8   103.5   12.4
    9   105.5   12.2
    10  105.5   12.1        

    MP <- NULL
    mapWorld <- borders("world", colour="gray50", fill="gray50")
    mp <- ggplot() +   mapWorld
for (i in 1:10) {
    MP[i] <- mp + geom_point(aes(x=df$x[i*10], y=df$y[i*10]) ,color="blue", size=1) 
    picture_name <- paste0("newsheet",i,".png")
    png(filename=picture_name)
    MP[[i]]
    dev.off()
}
    all_images <- list.files(path = "./", pattern = "*.png", full.names = T)
    P1 <- readPNG(all_images)

I expect a gif which shows one coordinate on the world map at a time as a blue dot, but the only thing I got to so far was that R interpreted P1 with only one image, with this error:

Warning message: In if (col == "jet") col = colorRampPalette(c("#00007F", "blue", : the condition has length > 1 and only the first element will be used


Solution

  • Here's how you can do it (based on the source to rgl::movie3d):

    filenames <- paste0("newsheet", 1:10, ".png")
    m <- magick::image_read(filenames[1])
    for (i in 2:10) 
      m <- c(m, magick::image_read(filenames[i]))
    m <- magick::image_animate(m, fps = 10, loop = 1, dispose = "previous")
    magick::image_write(m, "movie.gif")
    

    You put together your vector of filenames using list.files; I don't recommend that, because you don't really know what else is going to be in the directory, and they might not show up in the order you want. Since you generated the frames and know their filenames, use those names in the right order.