・お題:動くsinカーブのグラフを作成したい。
・少し調べてみたところ、matplotlib.animationのArtistAnimationとFuncAnimationという機能でグラフを動かせるらしい。
・まずArtistAnimationを使う。こちらは、紙芝居形式で、グラフを次々と表示させることで動かしてくれるらしい。一番最初の%matplotlib nbaggがないとグラフが動いてくれないので注意。
%matplotlib nbagg
import math
from matplotlib.animation import ArtistAnimation
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ims=[]#グラフをリスト形式で貯めるための空リストを作る
X=[i/10 for i in range(100)]
for i in range(100):
Y=[math.sin(j+i/10) for j in X]
img=ax.plot(X,Y,"blue")
ims.append(img)
ani = ArtistAnimation(fig, ims, interval=100)
#ani.save("test.gif")#gifなどでアニメーションを保存できる。
plt.show()
実行すると以下のような感じ。にょろにょろしている。
・次にFuncAnimationを使う。FuncAnimationは逐次的にプロットを追加していくことができるらしい。正直よく分からないが、先と似たようなグラフを描く。
%matplotlib nbagg
fig, ax = plt.subplots()
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
X = [j/10 for j in range(100)]
def update(i):
ax.cla()
Y = [math.sin(i/10 + j) for j in x]
ax.plot(X, Y, c="blue")
ani = FuncAnimation(fig, update, frames=50, interval=100)
plt.show()
これで概ね同じようなグラフを描くことができる(グラフは割愛)。
・FuncAnimationを弄っている過程で、(失敗して)以下のようなグラフが描けた。
%matplotlib nbagg
fig, ax = plt.subplots()
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
def update(i):
x = [j/10 for j in range(i,30+i)]
y = [math.sin(j) for j in x]
ax.plot(x, y, c="blue")
ani = FuncAnimation(fig, update, frames=50, interval=100)
#ani.save("test2.gif")
plt.show()
・なぜこんなことになってしまったのかよく分かっていないが、確かに逐次的な雰囲気を感じる。本来は軸を固定して使うのだろう。
謎は深まったが、グラフがうねうね動くのを見るのは楽しい。
おわり。