2017-04-21 31 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.001sのギャップのあと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")) 
関連する問題