动画包中的SaveGIF提供空白图像

时间:2019-04-29 23:08:52

标签: r

我必须从1990年1月到1999年12月从互联网上下载一些.png文件,对其进行裁剪,然后使用这些图像以.gif文件的形式创建动画。当我下载.png文件时,我按月和年命名,因此1990年1月的图像在我的计算机上命名为“ tmp011990.png”,1992年4月的图像命名为“ tmp041992.png”,以此类推。下载和裁剪的代码图像工作正常。

library(grid)
library(png)
library(animation)
library(ggplot2)

#example code for a single image using January 1990
#this code plots properly with proper cropping
img = readPNG("tmp011990.png")
g <- rasterGrob(img[100:400,40:320,])
ggplot() + annotation_custom(g)

#code for creating the animated GIF, gives a blank white image
saveGIF({
  for (n in 1990:1999) {
    for (i in 1:12) {
      imagename = sprintf("tmp%02i%d.png",i,n)
      print(imagename)
      img = readPNG(imagename)
      g <- rasterGrob(img[100:400,40:320,])
      ggplot() + annotation_custom(g)
    }
  }
}, interval = 0.1, movie.name="seaice.gif")

#alternate code for creating the GIF, displays only the last frame
saveGIF({
  for (n in 1990:1999) {
    for (i in 1:12) {
      imagename = sprintf("tmp%02i%d.png",i,n)
      print(imagename)
      img = readPNG(imagename)
      g <- grid.raster(img[100:400,40:320,])
      ggplot() + annotation_custom(g)
    }
  }
}, interval = 0.1, movie.name="seaice.gif")

saveGIF函数的预期结果是一个GIF文件,该文件是从1990年1月到1999年12月的所有120个月的动画。在循环中使用rasterGrob时,输出是空白的白色图像。在循环中使用grid.raster时,似乎将每个图像显示在最后一个图像的顶部,而不是替换它,因此输出是一个GIF,仅显示最后一个图像(“ tmp121999.png”)。我的循环是否有问题导致此问题?

1 个答案:

答案 0 :(得分:0)

没关系,问题解决了。使用saveGIF函数时,必须使用print(ggplot())。