2017-04-21 54 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"))