循环保存 ImageMagick 的每个 Dataframe 行图

Looping to Save Each Dataframe Row Plot for ImageMagik

尽量减少对第 3 方包的依赖并保留并行化代码的能力;下面这个可重现的示例旨在使用 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 更有效地按预期工作吗?

谢谢。

此代码将为一系列绘图创建一个 .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() 
}