2017-04-21 73 views
0

我有以下一段代码,但未按预期工作。逐步绘制使用系统暂停/睡眠

for(i in 3:nrow(pima_diabetes_kmean)){ 
    k.means.fit <- kmeans(pima_diabetes_kmean[1:i, c("Pregnancy", "Age")], 2) 
    plot(
    pima_diabetes_kmean[1:i, c("Pregnancy", "Age")], 
    col = alpha(k.means.fit$cluster, 0.2), 
    pch = 20, 
    cex = 3, main = "Clusters predicted by models" 
) 
    points(
    k.means.fit$centers, 
    pch = 4, 
    cex = 4, 
    lwd = 4, 
    col = "blue" 
) 
    Sys.sleep(0.001) 
} 

我可以删除循环并一次绘制它。但相反,我想绘制前3行数据,然后在0.001秒之后绘制4行,然后绘制5行,依此类推。它最终会绘制所有的数据点。

我想捕获这个过程,以便我可以创建一个视频或gif,显示每个点的添加如何影响集群化。但是这个绘图是一次绘制出来的,而不是逐步绘制,就好像for循环不存在一样。

+1

如果你想制作动画的情节,看'animation'包:这可能需要你调整你的代码了一下,但会使生产在视频最终容易得多。 – Marius

+0

0.001秒很短!也许增加到0.1秒 –

+0

是的,它现在正在工作。谢谢 – vipin8169

回答

0

这是它的工作原理:

png(file="kMeanPlot%03d.png", width=719, height=539) 
for(i in seq(3, nrow(pima_diabetes_kmean), by = 20)){ 
    k.means.fit <- kmeans(pima_diabetes_kmean[1:i, c("Pregnancy", "Age")], 2) 
    plot(
    pima_diabetes_kmean[1:i, c("Pregnancy", "Age")], 
    col = alpha(k.means.fit$cluster, 0.2), 
    pch = 20, 
    cex = 3, main = "Clusters predicted by models" 
) 
    points(
    k.means.fit$centers, 
    pch = 4, 
    cex = 4, 
    lwd = 4, 
    col = "blue" 
) 
} 
dev.off() 

# convert the .png files to one .gif file using ImageMagick. 
# The system()/shell() function executes the command as if it was done 
# in the terminal. the -delay flag sets the time between showing 
# the frames, i.e. the speed of the animation. 
# You will need to install the imagemagick for this 
# Following command for non-windows OS 
# system("C:/Program Files/ImageMagick-7.0.5-Q16/convert -delay 80 *.png fucked.gif") 
# Following command for Windows OS 
shell("convert -delay 40 *.png kMeanPlot.gif") 

# to not leave the directory with the single png files I remove them. 
file.remove(list.files(pattern="[kMeanPlot]*.png"))