我试图使用 caTools 包将多个图组合成一个 gif。
我的基本代码如下:
for(我在 1:100){
plot(....) // 绘制几个点和线,随着每个 i 略有变化
}
我想将这些组合成一个 gif,以查看情节的“演变”。
但是对于来自 caTools 的 write.gif(),我需要提供一个图像作为输入。对于每个 i,我如何将绘图转换为图像而不需要
请随时指出这是否是重复的。[从 R 中的一系列情节创建电影似乎没有回答这个问题]
编辑:基本上这需要我们将绘图转换为矩阵。由于每次有人保存情节时很可能会发生这种情况,因此应该不是很困难。但是我无法掌握如何准确地做到这一点。
我建议改用animation包和 ImageMagick:
library(animation)
## make sure ImageMagick has been installed in your system
saveGIF({
for (i in 1:10) plot(runif(10), ylim = 0:1)
})
Run Code Online (Sandbox Code Playgroud)
否则,您可以按照以下方式进行尝试(有很大的优化空间):
library(png)
library(caTools)
library(abind)
# create gif frames and write them to pngs in a temp dir
dir.create(dir <- tempfile(""))
for (i in 1:8) {
png(file.path(dir, paste0(sprintf("%04d", i), ".png")))
plot(runif(10), ylim = 0:1, col = i)
dev.off()
}
# read pngs, create global palette, convert rasters to integer arrays and write animated gif
imgs <- lapply(list.files(dir, full.names = T), function(fn) as.raster(readPNG(fn)))
frames <- abind(imgs, along = 3) # combine raster pngs in list to an array
cols <- unique(as.vector(frames)) # determine unique colors, should be less then 257
frames <- aperm(array(match(frames, cols) - 1, dim = dim(frames)), c(2,1,3)) # replace rgb color codes (#ffffff) by integer indices in cols, beginning with 0 (note: array has to be transposed again, otherwise images are flipped)
write.gif(
image = frames, # array of integers
filename = tf <- tempfile(fileext = ".gif"), # create temporary filename
delay = 100, # 100/100=1 second delay between frames
col = c(cols, rep("#FFFFFF", 256-length(cols))) # color palette with 256 colors (fill unused color indices with white)
)
# open gif (windows)
shell.exec(tf)
Run Code Online (Sandbox Code Playgroud)