今回はmatplotlibをオブジェクト指向スタイルで使ってみます。
plt.subplotsの理解
前回使ったplt.subplot()と似たメソッドのplt.subplots()を使います。
まずはJupyter notebookで下のように書いて実行してみましょう。
fig, ax = plt.subplots()
すると以下のように、出力されます。
また、変数を確認すると、
fig
このように真っ白な画面が出力されます。
同様にaxに関しても変数を確認してみると、
ax
<出力結果>
<matplotlib.axes._subplots.AxesSubplot at ...>
このようにaxesオブジェクトが表示されます。
ここからfigの変数には図全体を調節する__Figureオブジェクト__、
axの方にはグラフを描画する__axesオブジェクト__が入っていることがわかります。
ざっくり言えば、「グラフ用紙(axes)とグラフ全体のレイアウト(Figure)が用意されている。」
みたいなイメージです。
この用意したグラフ用紙と全体のレイアウトに対して、メソッドを追加していくことでグラフを調節できます。
具体的にオブジェクト指向スタイルで描画してみる。
1行2列のグラフ用紙にsin関数とcos関数を並べます。
1行のときは、axesオブジェクトの[]番目を指定します。
後でまた書きますが、複数行のときは[行,列]というように指定します。
x = np.arange(0,2*np.pi,0.01)
fig, ax = plt.subplots(1,2)
# 左のグラフ
ax[0].plot(x, np.sin(x))
ax[0].set_title("sinx")
# 右のグラフ
ax[1].plot(x, np.cos(x))
ax[1].set_title("cosx");
左のグラフと右のグラフが被っていますね。
これを避けるために、グラフの全体(Figureオブジェクト)に対してtight_layoutメソッドを使ってみましょう。
- 改善バージョン
x = np.arange(0,2*np.pi,0.01)
# facecolorで外側をskyblueにしてみた。
fig, ax = plt.subplots(1,2, facecolor='skyblue')
# 左のグラフ
ax[0].plot(x, np.sin(x))
ax[0].set_title("sinx")
# 右のグラフ
ax[1].plot(x, np.cos(x))
ax[1].set_title("cosx");
# グラフの配置が自動調整されます。
fig.tight_layout()
複数行のplot
グラフ用紙を選択するときは,[行の番号,列の番号]で指定します。
theta = np.arange(0,2*np.pi,0.01)
# 全体のサイズ調節
fig, ax = plt.subplots(2, 3, facecolor='skyblue')
# 右上[0,0]
ax[0,0].plot(theta, np.sin(theta))
ax[0,0].set_title("sin")
ax[0,0].grid()
# 中上[0,1]
ax[0,1].plot(theta, np.cos(theta))
ax[0,1].set_title("cos")
ax[0,1].grid()
# 右上[0,2]
ax[0,2].plot(theta-np.sin(theta), 1-np.cos(theta))
ax[0,2].set_title("cycloid")
ax[0,2].grid()
# 左下[1,0]
ax[1,0].plot(np.power(np.cos(theta),3), np.power(np.sin(theta),3))
ax[1,0].set_title("asteroid")
ax[1,0].grid()
# 中下[1,1]
ax[1,1].plot((1+np.cos(theta))*np.cos(theta), (1+np.cos(theta))*np.sin(theta))
ax[1,1].set_title("cardioid")
ax[1,1].grid()
# 右下[1,2]
theta2 = np.arange(0,10*np.pi,0.01) # インボリュート曲線用
ax[1,2].plot(np.cos(theta2)+theta2*np.sin(theta2), np.sin(theta2)-theta2*np.cos(theta2))
ax[1,2].set_title("involute of circle")
ax[1,2].grid()
# グラフ位置の自動調整
fig.tight_layout()
まとめ
今回はオブジェクト指向型の描画方法に関してやりました。
今までのようにplt.〜メソッド重ねていくのではなく、Figureオブジェクトとaxesオブジェクトをいじっていくことで描画していきます。
こちらの書き方の方が、細かいところまで指定できる、for文内で使用したり関数化しやすいなどのメリットがあるのである程度慣れたら、こちらの書き方に慣れた方が良いと思います。
matplotlibの構造を知りたいという方は下の記事を参照してください。(とてもわかりやすいです!!!)




