我必须从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”)。我的循环是否有问题导致此问题?
没关系,问题解决了。使用saveGIF函数时必须使用print(ggplot())。