Matplotlib 複数のグラフ#
※記事内に商品プロモーションを含むことがあります。
公開日
Matplotlibで複数のグラフを並べて表示するには、plt.subplots()
のnrows
やncols
オプションを用います。nrows
とncols
でそれぞれ縦方向と横方向のグラフの数を指定できます。
縦方向に並べる#
グラフを縦方向に並べる場合、nrows
に個数を指定します。以下に2つのグラフを縦に並べた例を示します。
import matplotlib.pyplot as plt
fig, ax = plt.subplots(nrows=2)
ax[0].plot([2, 3, 1])
ax[1].plot([3, 4, 0])
fig.tight_layout()
plt.show()

ncols
またはnrows
の片方のみ指定した場合、ax
はAxesオブジェクトの1次元配列となります。また、fig.tight_layout()
はグラフ間の間隔や余白を自動調節するためのコマンドです。
横方向に並べる#
グラフを横方向に並べる場合、ncols
に個数を指定します。以下に3つのグラフを横に並べた例を示します。
fig, ax = plt.subplots(ncols=3)
ax[0].plot([2, 3, 1])
ax[1].plot([3, 4, 0])
ax[2].plot([0, 3, 1])
fig.tight_layout()
plt.show()

縦・横方向に並べる#
グラフを縦・横の両方向に並べる場合、nrows
とncols
に個数を指定します。以下に縦と横にそれぞれ2つずつ並べた例を示します。
fig, ax = plt.subplots(nrows=2, ncols=2)
ax[0, 0].plot([2, 3, 1])
ax[0, 1].plot([3, 4, 0])
ax[1, 0].plot([0, 3, 1])
ax[1, 1].plot([2, 1, 0])
fig.tight_layout()
plt.show()

nrows
とncols
の両方を指定した場合、ax
はAxesオブジェクトの2次元配列になります。ax[X, Y]
は縦にX
番目、横にY
番目(いずれも0始まり)のAxesオブジェクトを示します。
共通な軸の範囲#
複数のグラフで軸が共通している場合、plt.subplots()
でsharex
やsharey
オプションを使用して軸の範囲を揃えることが出来ます。sharex
, sharey
オプションに指定可能な値を以下の表に示します。
値 |
説明 |
---|---|
|
軸を揃えない(デフォルト) |
|
全グラフの軸を揃える |
'row' |
横方向のグラフのみ軸を揃える |
'col' |
縦方向のグラフのみ軸を揃える |
sharex=True
とした場合、最も下のグラフのみx軸の値が表示されます。同様にsharey=True
とした場合、最も左のグラフのみy軸の値が表示されます。さらに、全てのグラフでx軸やy軸の範囲も共通となります。
fig, ax = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
ax[0, 0].plot([2, 3, 1])
ax[0, 1].plot([3, 4, 0])
ax[1, 0].plot([0, 3, 1])
ax[1, 1].plot([2, 1, 0])
fig.tight_layout()
plt.show()

上のグラフと同じデータを用いて、sharey='row'
に変更した例を以下に示します。こちらでは、行ごとにグラフのy軸の範囲を共通にします。すなわち、上2つのグラフと下2つのグラフで、それぞれ異なる軸の範囲となっています。
fig, ax = plt.subplots(nrows=2, ncols=2, sharex=True, sharey='row')
ax[0, 0].plot([2, 3, 1])
ax[0, 1].plot([3, 4, 0])
ax[1, 0].plot([0, 3, 1])
ax[1, 1].plot([2, 1, 0])
fig.tight_layout()
plt.show()
