如何在 R 中从多个 PNG 创建 GIF?

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

我开发了一个代码来在世界地图上创建动画轨迹。我首先将其保存为 .png,然后想将其转换为 .gif 文件。

我下载了 ImageMagick 并尝试了此处的建议:Creating a Movie from a Series of Plots in R 但无法正常工作。有人可以帮助我吗?

这是我的图书馆:

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

我的数据框是坐标,所以像这样:

            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)

我希望得到一个 gif,它一次在世界地图上显示一个坐标作为蓝点,但到目前为止我唯一得到的是 R 只用一张图像解释 P1,并出现以下错误:

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

以下是您的操作方法(基于 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")

您使用 list.files 将文件名向量放在一起;我不建议这样做,因为您真的不知道目录中还会有什么,而且它们可能不会按照您想要的顺序显示。由于您生成了帧并知道它们的文件名,因此请按正确的顺序使用这些名称。