LoginSignup
1

More than 3 years have passed since last update.

Rのplotをfor文で書いてgifにしたい【R言語】

Posted at

TEST.gif

plotをgifにしたい時

最小二乗法の更新していく過程をgifにしたかった
plotが追加されていく過程をわかりやすく図にしたい

パッケージの"animation"にお願いする

注意!!! for文で200以上を超えると高確率でフリーズします

library("animation")

x<-sort(rnorm(1000,50,10))
y<-sort(rnorm(1000,30,8)) + rnorm(1000,5,5)
plot(x,y,xlab="面積[m^2]",ylab="値段[円]",xlim=c(0,90),ylim=c(0,70))
abline(lm(y~x),col="red")

bind_x<-NULL
bind_y<-NULL

saveGIF({

  for(i in 1:200){
    px<-rnorm(1,60,5)
    py<-rnorm(1,25,5)
    bind_x<-c(bind_x,px)
    bind_y<-c(bind_y,py)
    plot(x,y,xlab="面積[m^2]",ylab="値段[円]",xlim=c(0,90),ylim=c(0,70))
    points(bind_x,bind_y,col="red")
    lx<-c(x,bind_x)
    ly<-c(y,bind_y)
    abline(lm(ly~lx))
  }

}, interval = 0.5, movie.name = "liner_regression.gif")

これでgifに保存できている。

基本構造

saveGIF({

#for文をここに記述

}, interval = 0.5, movie.name = "liner_regression.gif")

intervalで画像の更新秒数
nameは保存名

以上

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1