初心者のためのpython入門

自分がつまづいたところやつまづきやすいところを中心に書いていきます。また、役に立つライブラリの紹介などをしていきます。

matplotlib[2]

前書き

今回もmatplotlibについて説明します。

複数の図を同時に[1]

複数の図の描画です。サンプルを見ましょう。

# multigraph.py
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 3, figsize=(8, 6), sharex=True, sharey=True) # 図を2行3列に大きさ(8, 6)で分割
nrow, ncol = ax.shape # nrow=2, ncol=3

N = 50
for i in range(nrow):
    for j in range(ncol):
        x = np.random.rand(N) # 50個の乱数生成
        y = (j + 1) * (i + 1) * np.random.rand(N)
        ax[i][j].scatter(x, y) # 散布図
        ax[i][j].grid(True) # グリッド線
        ax[i][j].set_xlabel('x') # x軸ラベル
        ax[i][j].set_ylabel('y') # y軸ラベル
        ax[i][j].set_title('[' + str(i) + ',' + str(j) + ']') # タイトル

plt.show() # グラフを描画

上記のコードを実行すると以下のグラフが表示されます。コードの説明はほとんどコメントに書いてある通りです。
subplots関数の戻り値は、1つのFigureクラスのインスタンスと4つのAxesSubplotクラスのインスタンスであり、それをfigとaxで受け取っています。subplotsの引数のsharexとshareyをTrueにすることにより、全てのグラフでx軸とy軸の範囲を揃えることができます。また、今回の例ではfigは使っていません。
axはAxesSubplotのインスタンスの配列であるのでax[行][列](またはax[行, 列])と指定することにより、それぞれのインスタンスにアクセスしてグラフに描画するものを指定しています。

f:id:tiginkgo:20180310145249p:plain

複数の図を同時に[2]

先程とは少し異なる方法です。サンプルを見ましょう。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 11)
y = x
plt.figure(figsize=(8 ,6))
plt.subplot(221) # 2行2列分割の1枚目
plt.plot(x, y, marker='o', color='r')
plt.grid(True)
plt.title('y=x')
plt.xlabel('x')
plt.ylabel('y')

plt.subplot(222) # 2行3列分割の2枚目
plt.plot(x, 2*y, marker='x', color='b')
plt.grid(True)
plt.title('y=2x')
plt.xlabel('x')
plt.ylabel('y')

plt.subplot(223) # 2行3列分割の3枚目
plt.plot(x, 3*y, marker='s', color='y')
plt.grid(True)
plt.title('y=3x')
plt.xlabel('x')
plt.ylabel('y')

plt.subplot(224) # 2行3列分割の4枚目
plt.plot(x, 4*y, marker='^', color='g')
plt.grid(True)
plt.title('y=4x')
plt.xlabel('x')
plt.ylabel('y')

plt.subplots_adjust(wspace=0.3, hspace=0.5) #平行方向に0.3, 垂直方向に0.5のスペースを空ける
plt.show()

上記のコードを実行すると以下のグラフが表示されます。コードの説明はほとんどコメントに書いてある通りです。
plt.subplot()は、引数に行数、列数、プロット番号を順に指定します。

f:id:tiginkgo:20180310151234p:plain

簡単なアニメーション

普段はあまり使いませんが、アニメーションの描画もできます。サンプルを見ましょう。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

N = 100 # フレーム数

x = np.arange(0, 10, 0.1)
xmin, xmax = 0, 10

def animate(nframe): #描画関数
    plt.cla() # Axesオブジェクトのクリア
    y = np.sin(x - nframe)
    plt.plot(x, y, "r")
    plt.xlim(xmin, xmax)
    plt.ylim(-1.1, 1.1)
    plt.title('N=%s' % nframe)

fig = plt.figure() # Figureクラスのインスタンス化
anim = animation.FuncAnimation(fig, animate, np.arange(1, N+1)) # アニメーションのインスタンス化
                                                                # 引数は(Figeureオブジェクト, 描画関数, フレーム番号)
# anim.save('sin.gif', writer='imagemagik', fps=20) ImageMagickがあれば、gif形式で保存できる
plt.show()

上記の実行結果は、興味があれば実行して確かめて下さい。animate関数の中身を書き換えることにより様々なアニメーションを作成できます。

最後に

お疲れ様でした。これでmatplotlibの説明は終わりです。次回からは、ライブラリの説明を中断して入出力の説明をします。