グラフの分割

for 文を利用したグラフでは一つのグラフ内に複数の折れ線グラフを表示しました. 個別に表示する場合にはどのようになるでしょうか. 一つの方法として,以下の用に複数のグラフを個別に作成することも可能です. (先に保存先のディレクトリ result/multi_plot を作成しておきましょう.)

for x in df.columns[1:]:
    plt.plot(df['Date'],df[x])
    plt.title(x)
    plt.xticks(rotation=15)
    plt.savefig('result/multi_plot/' + x + '.png')
    plt.close()
保存された10個のグラフ

しかし,レポートなどに10枚の画像を貼り付けるのは手間がかかりますし,余白など無駄も多いです.

matplotlibには1枚の画像を分割して複数のグラフを載せるためのメソッド.subplots()があるので,関連するグラフや比較のためのグラフなどはできるだけ1枚の画像に集約しましょう.

.subplots()は1枚の画像をn行,n列に分割し,それぞれの領域にグラフを描画します.

各領域は axesなどと呼ばれ,画像全体をfigureなどと呼びます. 利用するためには,まず fig, axes = plt.subplots()の形で宣言します. 引数として,行数はnrows=,列数はncols=にそれぞれintで指定します.

FigureとAxes

fig, axes = plt.subplots(nrows= 5 #行数の指定
                       ,ncols= 2 #列数の指定
                        )

宣言のあと,各領域のグラフを axes[行,列]の形で指定していきます.行や列は0から始まるので注意してください.

axes[0,0].plot(df['Date'],df['Location_1'],label='Location_1')
axes[0,1].plot(df['Date'],df['Location_2'],label='Location_2')
axes[1,0].plot(df['Date'],df['Location_3'],label='Location_3')
axes[1,1].plot(df['Date'],df['Location_4'],label='Location_4')
axes[2,0].plot(df['Date'],df['Location_5'],label='Location_5')
axes[2,1].plot(df['Date'],df['Location_6'],label='Location_6')
axes[3,0].plot(df['Date'],df['Location_7'],label='Location_7')
axes[3,1].plot(df['Date'],df['Location_8'],label='Location_8')
axes[4,0].plot(df['Date'],df['Location_9'],label='Location_9')
axes[4,1].plot(df['Date'],df['Location_10'],label='Location_10')
plt.show()

以下のようなグラフが作成されます. しかし, 少し見にくいですね.

subplots

.subplots(sharex=True)とすると,x軸を共有することができます.今回のグラフはx軸がすべて同じなので,共有してみましょう. また,それぞれのグラフにタイトルを付けてみます. 更に,一つ一つ手で入力するのは手間なのでfor文を利用してみましょう.

タイトルを付けるには今までのplt.title()ではなくaxes[r,c].set_title()になります. axes毎の要素に関しては公式サイトを参考にしてください.

axesの要素(https://matplotlib.orgより)
fig, axes = plt.subplots(nrows= 5 #行数の指定
                        ,ncols= 2 #列数の指定
                        ,sharex=True)

count = 0
for i in range(5):
    for j in range(2):
        col = df.columns[1:]
        axes[i,j].plot(df['Date'],df[col[count]])
        axes[i,j].set_title(col[count])
        axes[i,j].tick_params(axis='x', rotation=15)
        count +=1
plt.show()
subplots

グラフ全体の要素はfig.の形で指定します. タイトルを付ける場合はfig.suptitle('title')となります.

fig, axes = plt.subplots(nrows= 5 #行数の指定
                        ,ncols= 2 #列数の指定
                        ,sharex=True)

count = 0
for i in range(5):
    for j in range(2):
        col = df.columns[1:]
        axes[i,j].plot(df['Date'],df[col[count]])
        axes[i,j].set_title(col[count])
        axes[i,j].tick_params(axis='x', rotation=15)
        count +=1
fig.suptitle('subplots title')
plt.show()
subplots
  • flatten()

for文を二重ループで記述するのは大変なので,しばしばaxes.flatten()を利用して,連番に変換すると便利です.

flatten
fig, axes = plt.subplots(nrows= 5 #行数の指定
                        ,ncols= 2 #列数の指定
                        ,sharex=True)

#連番に変換
axes = axes.flatten()
for i in range(10):
    col = df.columns[1:][i] #countをiで共通化
    axes[i].plot(df['Date'],df[col])
    axes[i].set_title(col)
    axes[i].tick_params(axis='x', rotation=15)
fig.suptitle('subplots title')
plt.show()
ce0f13b2-4a83-4c1c-b2b9-b6d18f4ee6d2