使用.png文件

时间:2018-03-16 11:39:18

标签: r animation imagemagick png gif

示例数据

 location <- c("A","B","C")
 years <- c(2001,2002,2003)

 for(l in seq_along(location)){
    for(y in seq_along(years)){
       loc <- location[l]
       yr <- years[y]
       png(paste0(loc,".",yr,".png"))
       plot(rnorm(10))
       dev.off()
   }
   }

对于每个位置X年组合,我生成了png文件。我的目标是将每个位置,所有年份组合在一个gif.file中以显示为动画。

我这样做

  library(magick)

  # convert each png file as magick object 
  for(l in seq_along(location)){
    for(y in seq_along(years)){
       loc <- location[l]
       yr <- years[y]

       png.dat <- image_read(paste0(loc,".",yr,".png"))

       assign(paste0(loc,".",yr),png.dat)
   }}

这为我提供了关于位置A,B和C的以下文件:

A.2001,A.2002,A.2003 B.2001,B.2002,B.2003 C.2001,C.2002,C.2003

  # stack the objects for one location, and create animation
  A.c <- c(A.2001,A.2002,A.2003)
  A.img <- image_scale(A.c)
  A.ani <- image_animate(A.img, fps = 1, dispose = "previous")
  image_write(A.ani, paste0("A_animation.gif"))

  # repeat for B and C
   B.c <- c(B.2001,B.2002,B.2003)
   B.img <- image_scale(B.c)
   B.ani <- image_animate(B.img, fps = 1, dispose = "previous")
   image_write(B.ani, paste0("B_animation.gif"))

 # stack the objects for one location, and create animation
  C.c <- c(C.2001,C.2002,C.2003)
  C.img <- image_scale(C.c)
  C.ani <- image_animate(C.img, fps = 1, dispose = "previous")
  image_write(C.ani, paste0("C_animation.gif"))

enter image description here

enter image description here

enter image description here

我的问题是,实际上我有超过100个地点和30年。因此,上面创建动画的步骤变为手动。有没有人有更快的方法来完成上述任务。

1 个答案:

答案 0 :(得分:1)

您可以使用magick中的image_join将“ magick-image”类的对象列表强制转换为多帧图像。

在您的示例中,这是我的处理方式:

library(purrr)
library(magick)

location <- c("A","B","C")
years <- c(2001,2002,2003)

df <- data.frame(loc = character(0), yr = integer(0), file = character(0))

for(l in seq_along(location)){
  for(y in seq_along(years)){
    loc <- location[l]
    yr <- years[y]
    png(paste0(loc,".",yr,".png"))
    plot(rnorm(10))
    dev.off()
  }
}

df <- expand.grid(loc = location,
                  yr = years)
df$file = paste0(df$loc,".",df$yr,".png")

df

#  loc   yr       file
# 1   A 2001 A.2001.png
# 2   B 2001 B.2001.png
# 3   C 2001 C.2001.png
# 4   A 2002 A.2002.png
# 5   B 2002 B.2002.png
# 6   C 2002 C.2002.png
# 7   A 2003 A.2003.png
# 8   B 2003 B.2003.png
# 9   C 2003 C.2003.png

locations <- unique(df$loc)

for(i in 1:length(locations)) {
  images <- map(df$file[df$loc == locations[i]], image_read)
  images <- image_join(images)
  animation <- image_animate(images, fps = 1)
  image_write(animation, paste0(locations[i], ".gif"))
}