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

标签 r imagemagick

我开发了一个代码来在世界地图上创建动画轨道。我首先将其保存为 .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将文件名向量组合在一起;我不建议这样做,因为您真的不知道目录中还会有什么,而且它们可能不会按您想要的顺序显示。由于您生成了帧并知道它们的文件名,因此请按正确的顺序使用这些名称。

关于r - 如何在 R 中从多个 PNG 创建 GIF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58031910/

相关文章:

r - R 中两个类别的预测类别概率

r - 带有 $\lambda = 0$ 的 LASSO 和 OLS 在 R glmnet 中产生不同的结果

r - 使用same()忽略列表中项目的顺序

batch-file - Image Magick Convert -profile 后替换原始 jpg

pdf - GhostScript 替代方案

根据模式重命名列表中命名向量的名称

r - 删除 R 中某个点之后的行

php - xampp无法加载imagick-不兼容的库版本

python - 获取通过 Wand 转换的结果文件列表

imagemagick - 调整大小以适合盒子并将背景设置为黑色在 "empty"部分