r - 循环保存 ImageMagik 的每个数据帧行图
问题描述
最小化第三方包依赖并保留并行化代码的能力;下面这个可复制的示例旨在使用 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()
}
推荐阅读
- android - 在 Android Jetpack Compose 项目中,isLoading 的值会一直为真吗?
- activemq - activemq 内存使用与队列的可用内存
- slack - 无法使用 Slack 提醒(/remind @group #channel "Message")
- python - 如何让用户从任何目录上传 CSV 到 MongoDB
- reactjs - 在 React 中使用 Tailwind 时如何关闭子模式而不关闭其父模式
- php - 将特定列从表复制到表
- ansible - 在 Ansible 中,可以反向循环遍历字典吗?
- android - ViewModel 和 LiveData 不会立即从 Firebase 实时数据库中获取更改
- arrays - 角管 - 排序不区分大小写
- amazon-web-services - 上传开始的 AWS S3 事件通知