循环保存ImageMagik的每个数据框行图

时间:2018-07-24 20:11:13

标签: r loops animated-gif

为了最大程度地减少第三方包装的依赖性,并保留并行化代码的能力;下面的此可复制示例旨在使用R的基本图形(无Tidyverse或GGPlot)为绘图的每个行步骤创建png图像。

但是,它将为每个图像生成整个系列,而不是所需的迭代构建:

# 
setwd("///images") 
data(mtcars) # load DF 

frames = 50 # set image qty rate 

for(i in 1:frames){
 # creating a name for each plot file with leading zeros
 if (i < 10) {name = paste('000',i,'plot.png',sep='')}
 if (i < 100 && i >= 10) {name = paste('00',i,'plot.png', sep='')}
 if (i >= 100) {name = paste('0', i,'plot.png', sep='')} 
 png(name) 
 # plot(mtcars$mpg,type="l") 
 plot(mtcars$mpg)
 dev.off() 
} 

my_cmd <- 'convert *.png -delay 5 -loop 5 mpg.gif'
system(my_cmd) 
# 

我自己未能成功解决问题的尝试包括:

1)删除帧迭代并使用nrows(mtcars)作为循环控制代理? 2)以某种方式为每个绘图调用引用行索引? 3)在每个图之后在循环内插入sleep()调用吗? 4)使用apply()函数而不是循环吗?

是否有任何指针或其他编码可以提高R的效率,以使其按预期工作?

谢谢。

1 个答案:

答案 0 :(得分:1)

此代码将为一系列绘图创建一个.png文件,其中每个连续绘图上都有一个附加点:

# load data
data(mtcars)

# specify number of files to create (one per row of mtcars)
frames <- nrow(mtcars)

# figure out how many leading zeros will be needed in filename
ndigits <- nchar(as.character(frames))
for(i in 1:frames){
    # name each file
    zeros <- ndigits - nchar(as.character(i))
    ichar <- paste0(strrep('0',zeros), i)
    name  <- paste0(ichar, 'plot.png')
    # plot as .png
    png(filename = name)
    plot(x=1:i, y=mtcars$mpg[1:i], pch=20, col="blue",
         xlim=c(0,frames), ylim=range(mtcars$mpg))
    dev.off() 
}