matplotlibをオブジェクト指向スタイルで使う その2


このエントリーをはてなブックマークに追加

前にmatplotlibをオブジェクト指向スタイルで使う - minus9d's diaryという記事を書きました。しかし、matplotlib によるデータ可視化の方法 (1) - Qiita および Why do many examples use "fig, ax = plt.subplots()" in Matplotlib/pyplot/python - Stack Overflow によると、plt.subplots()という関数を使うと、より簡潔に書けるようです。この記事ではplt.subplots()の例を紹介します。

なお、以下のコード片では、全て冒頭に

import matplotlib.pyplot as plt
import numpy as np

と書かれているものとします。

一つの図に一つのグラフの場合

まず、一つの図と一つのグラフ領域を持つ絵を、私が前の記事で紹介した方法で描くと以下のようになります。

x = np.arange(0, 4, 0.1)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, x**2)

今回紹介するplt.subplots()を使うと、以下のように一行減り簡潔に書けます。

x = np.arange(0, 4, 0.1)
fig, ax = plt.subplots()
ax.plot(x, x**2)

参考までに、plt.show()して表示されるグラフを示します。 f:id:minus9d:20160421213310p:plain

一つの図に複数のグラフの場合

subplots()に引数を入れると、複数のグラフ領域を持つ絵もかけます。例えば

x = np.arange(0, 4, 0.1)
fig, axes = plt.subplots(2, 2)
for j in range(2):
    for i in range(2):
        ax = axes[j, i]
        ax.plot(x, x**(j*2+i))

とすると、以下のような絵がかけます。

f:id:minus9d:20160420230454p:plain

同じことを行う以下のコードと比較してみてください。

x = np.arange(0, 4, 0.1)

fig1 = plt.figure(1)
ax1 = fig1.add_subplot(221)
ax1.plot(x, x**0)

ax2 = fig1.add_subplot(222)
ax2.plot(x, x**1)

ax3 = fig1.add_subplot(223)
ax3.plot(x, x**2)

ax4 = fig1.add_subplot(224)
ax4.plot(x, x**3)

(2016/4/21追記)ブコメでもっとよい書き方を教えていただきました、ありがとうございます。add_subplot()に3つの引数を与えることでループ化が可能だそうです。

x = np.arange(0, 4, 0.1)
fig1 = plt.figure(1)
for i in range(4):
    ax = fig1.add_subplot(2,2,i+1)
    ax.plot(x, x**i)

もっともこのようにループ化した場合であっても、figureの作成処理とaxの作成処理の2回が必要であり、subplots()を使う場合より繁雑なところは変わりません。