[1-1] 動画作成用のモジュールをインポートして、動画を表示可能なモードにセットします。
In [1]:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from numpy.random import randint
%matplotlib nbagg
[1-2] x軸上を一定速度で移動するボールの動画を描きます。
動画のGIFファイル「animation01.gif」も同時に作成します。
In [2]:
fig = plt.figure(figsize=(6,2))
subplot = fig.add_subplot(1,1,1)
subplot.set_xlim(0,50)
subplot.set_ylim(-1,1)
x = 0
images = []
for _ in range(50):
image = subplot.scatter([x],[0])
images.append([image])
x += 1
ani = animation.ArtistAnimation(fig, images, interval=100)
ani.save('animation01.gif', writer='imagemagick', fps=10)
[1-3] 3個のランダムウォークの動画を描きます。
動画のGIFファイル「animation02.gif」も同時に作成します。
In [3]:
fig = plt.figure(figsize=(6,4))
subplot = fig.add_subplot(1,1,1)
y1s, y2s, y3s = [], [], []
y1, y2, y3 = 0, 0, 0
images = []
for t in range(100):
y1s.append(y1)
y2s.append(y2)
y3s.append(y3)
image1, = subplot.plot(range(t+1), y1s, color='blue')
image2, = subplot.plot(range(t+1), y2s, color='green')
image3, = subplot.plot(range(t+1), y3s, color='red')
images.append([image1, image2, image3])
y1 += randint(-1,2)
y2 += randint(-1,2)
y3 += randint(-1,2)
ani = animation.ArtistAnimation(fig, images, interval=100)
ani.save('animation02.gif', writer='imagemagick', fps=10)