[3-1] 動画作成用のモジュールをインポートして、動画を表示可能なモードにセットします。


In [1]:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
%matplotlib nbagg

[3-2] x=0〜1の範囲で棒グラフを描いて面積を計算する関数integralを定義します。


In [2]:
def integral(f, filename):
    fig = plt.figure(figsize=(4,4))
    images = []
    step = 0.5
    
    for _ in range(10):
        subplot = fig.add_subplot(1,1,1)
        subplot.set_xlim(0, 1)
        subplot.set_ylim(0, 1)
        linex = np.linspace(0, 1, 100)
        subimages = []

        im, = subplot.plot(linex, f(linex), color='blue')
        subimages.append(im)

        area = 0
        for x0 in np.arange(0, 1, step):
            rect = plt.Rectangle((x0,0), step, f(x0), alpha=0.5)
            im = subplot.add_patch(rect)
            subimages.append(im)
            area += step * f(x0)
        im = subplot.text(0.3, 1.05, ('area = %f' % area))
        subimages.append(im)
        images.append(subimages)
        step *= 0.5

    ani = animation.ArtistAnimation(fig, images, interval=1000)
    ani.save(filename, writer='imagemagick', fps=1)
    return ani

[3-3] 二次関数 y=x*x を用意して、関数integralを呼び出します。

GIF動画ファイル「integral01.gif」が作成されます。


In [3]:
def f(x):
    y = x*x
    return y

integral(f, 'integral01.gif')


Out[3]:
<matplotlib.animation.ArtistAnimation at 0x2dbef10>

[3-4] 円弧を表す関数を用意して、関数integralを呼び出します。

GIF動画ファイル「integral02.gif」が作成されます。


In [4]:
def f(x):
    y = np.sqrt(1.0-x*x)
    return y

integral(f, 'integral02.gif')


Out[4]:
<matplotlib.animation.ArtistAnimation at 0x86c2210>