将多个图组合成一个gif

问题描述 投票:2回答:3

我试图使用caTools包将多个图组合成一个gif。

我的基本代码如下:

 for( i in 1:100){
     plot(....) // plots few points and lines, changes slightly with each i
  }

我想将这些与gif结合起来,看看情节的“演变”。

但是对于来自caTools的write.gif(),我需要提供一个图像作为输入。对于每个i,如何将绘图转换为无图像

  1. 保存到光盘作为中间步骤
  2. 取决于ImageMagick或类似的外部依赖项。

请随时指出这是否重复。 [Creating a Movie from a Series of Plots in R似乎没有回答这个]

编辑:基本上这需要我们将绘图转换为矩阵。由于这很可能发生在每次有人保存情节时,这应该不是很困难。但是,我无法掌握如何做到这一点。

r gif
3个回答
4
投票

我建议使用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)
})

否则你可以在这个静脉中尝试它(有足够的优化空间):

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)  

1
投票

那是你在找什么?

   library(ggplot2)
   a <- 0:10
    df <- data.frame(a=a,b=a)
    steps <-function(end){
      a <- ggplot(df[1:end,], aes(a,b)) + 
        geom_point() + 
        scale_x_continuous(limits=c(0,10)) +
        scale_y_continuous(limits=c(0,10))
      print(a)
    }
    gif <- function() {
      lapply(seq(1,11,1), function(i) {
        steps(i)
      })
    }
    library(animation)
    saveGIF(gif(), interval = .2, movie.name="test.gif")

0
投票

我喜欢@ ttlngr的答案,但我想要一些更简单的东西(它仍然使用ImageMagick)。

saveGIF({
  for (i in 1:10){  
    a <- ggplot(df[1:i,], aes(a,b)) + 
      geom_point() + 
      scale_x_continuous(limits=c(0,10)) +
      scale_y_continuous(limits=c(0,10))
  print(a)}
}, interval = .2, movie.name="test.gif")
© www.soinside.com 2019 - 2024. All rights reserved.