将多个情节组合为一个gif [英] combine multiple plots to a gif
问题描述
我正在尝试使用caTools软件包将多个绘图组合成一个gif.
Im trying to use the caTools package to combine multiple plots into a gif.
我的基本代码如下:
for( i in 1:100){
plot(....) // plots few points and lines, changes slightly with each i
}
我想将它们组合成一个gif,以查看剧情的演变".
I would like to combine these to a gif to see the "evolution" of the plot.
但是对于caTools的write.gif(),我需要提供一个图像作为输入. 对于每个i,我如何将绘图转换成图像而无需
However for write.gif() from caTools, I need to give an image as an input. For each i, how do I convert the plot into an image without
- 保存到光盘作为中间步骤
- 取决于ImageMagick或类似的外部依赖项.
请随时指出是否重复. [根据R中的一系列剧情制作电影似乎没有回答这个问题]
Please feel free to point out if this is a duplicate. [ Creating a Movie from a Series of Plots in R doesnt seem to answer this ]
基本上,这需要我们将绘图转换为矩阵.由于每次有人保存地块时很可能会发生这种情况,所以这应该不是很困难.但是,我无法掌握具体的操作方法.
Basically this requires us to convert a plot to a matrix. Since this very likely happens every time someone saves a plot, it should not be very difficult. However Im not able to get hold of how to exactly do this.
推荐答案
我建议使用animation
包和ImageMagick代替:
I suggest using the animation
package and ImageMagick instead:
library(animation)
## make sure ImageMagick has been installed in your system
saveGIF({
for (i in 1:10) plot(runif(10), ylim = 0:1)
})
否则,您可以尝试这样做(有很多优化的余地):
Otherwise you could try it in the veins of this (plenty of room for optimization):
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)
这篇关于将多个情节组合为一个gif的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!