Matplotlib subplots() 関数


Matplotlib リファレンスドキュメント

subplots()Figure と一連の Axes サブプロットを作成する推奨方法であり、1回の呼び出しでキャンバスとサブプロットの作成を完了できます。

これは Matplotlib のオブジェクト指向インターフェースの中核となるエントリ関数です。

関数定義

pyplot インターフェース

matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False,
    sharey=False, squeeze=True, width_ratios=None,
    height_ratios=None, subplot_kw=None, gridspec_kw=None,
    **fig_kw)

Figure メソッド

Figure.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False,
    squeeze=True, width_ratios=None, height_ratios=None,
    subplot_kw=None, gridspec_kw=None)

パラメータの説明

パラメータ型説明
nrowsintサブプロットの行数、デフォルトは1
ncolsintサブプロットの列数、デフォルトは1
sharex / shareybool または strx/y 軸を共有するかどうか。'all'/'row'/'col'/'none' またはブール値を渡せます。
squeezeboolTrue の場合、単一行・単一列のときに余分な次元を自動的に削除します。デフォルトは True。
width_ratioslist各列の幅の比率。例: [1, 2] は2列目が1列目の2倍の幅であることを示します。
height_ratioslist各行の高さの比率。例: [2, 1] は1行目が2行目の2倍の高さであることを示します。
subplot_kwdictサブプロット作成に渡すパラメータ。例: dict(projection='polar') で極座標サブプロットを作成。
gridspec_kwdictGridSpec に渡すパラメータ。例: dict(hspace=0.3, wspace=0.3) でサブプロット間の間隔を設定。
**fig_kwdictFigure 作成に渡すパラメータ。例: figsize=(8,6), dpi=100, layout='constrained'

subplots() の戻り値はタプルです。(fig, ax)1行1列のとき、ax は単一の Axes オブジェクトです。複数行・複数列のとき、ax は Axes の2次元配列です。


使用例

例 1:単一サブプロット

実例

import matplotlib.pyplot as plt
import numpy as np

# 単一サブプロットを作成(最も一般的な書き方)
fig, ax = plt.subplots(figsize=(6, 4), layout='constrained')

x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x))
ax.set_title('Single Subplot')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
ax.grid(True, alpha=0.3)
plt.show()

例2:1行複数列 / 1列複数行

実例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

# 1行3列
fig, axes = plt.subplots(1, 3, figsize=(12, 4),
                          layout='constrained')

# axes は1次元配列
axes[0].plot(x, np.sin(x), color='blue')
axes[0].set_title('sin(x)')

axes[1].plot(x, np.cos(x), color='red')
axes[1].set_title('cos(x)')

axes[2].plot(x, np.tan(x), color='green')
axes[2].set_title('tan(x)')
axes[2].set_ylim(-5, 5)  # y の範囲を制限

for ax in axes:
    ax.set_xlabel('x')
    ax.grid(True, alpha=0.3)

fig.suptitle('Three Subplots in One Row', fontsize=14)
plt.show()

例 3:2x2 グリッド + 幅と高さの比率

実例

import matplotlib.pyplot as plt
import numpy as np

# 幅と高さの比率:1行目はより高く、2列目はより広い
fig, axes = plt.subplots(2, 2,
                          figsize=(10, 8),
                          width_ratios=[1, 2],   # 2列目の幅は1列目の2倍
                          height_ratios=[2, 1],   # 1行目の高さは2行目の2倍
                          layout='constrained',
                          sharex='col',           # 各列で x 軸を共有
                          sharey='row')           # 各行で y 軸を共有

x = np.linspace(0, 10, 100)

# axes は2次元配列、axes[row, col]
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('sin(x)')

axes[0, 1].plot(x, np.cos(x), 'orange')
axes[0, 1].set_title('cos(x)')

axes[1, 0].plot(x, np.sin(2*x), 'green')
axes[1, 0].set_title('sin(2x)')

axes[1, 1].plot(x, np.cos(2*x), 'red')
axes[1, 1].set_title('cos(2x)')

fig.suptitle('2x2 Grid with Width/Height Ratios', fontsize=14)
plt.show()

例 4:sharex と sharey で軸を共有

実例

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)

# x 軸を共有して時系列を比較しやすくする
fig, axes = plt.subplots(3, 1, figsize=(8, 6),
                          sharex=True,            # x 軸を共有
                          layout='constrained')

t = np.linspace(0, 20, 200)

# 3つのサブプロットが x 軸を共有し、時刻を揃える
axes[0].plot(t, np.sin(t), 'blue')
axes[0].set_ylabel('Signal 1')
axes[0].grid(True, alpha=0.3)

axes[1].plot(t, np.cos(t * 1.5), 'green')
axes[1].set_ylabel('Signal 2')
axes[1].grid(True, alpha=0.3)

axes[2].plot(t, np.sin(t * 0.7) + np.cos(t * 1.3), 'red')
axes[2].set_xlabel('Time (s)')
axes[2].set_ylabel('Signal 3')
axes[2].grid(True, alpha=0.3)

fig.suptitle('Shared X-Axis: Three Time Series', fontsize=14)
plt.show()

例 5:極座標サブプロット

実例

import matplotlib.pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
    subplot_kw={'projection': 'polar'},  # 2つとも極座標
    layout='constrained')

theta = np.linspace(0, 2 * np.pi, 100)

# 左の図:バラ曲線
r1 = np.abs(np.sin(3 * theta))
ax1.plot(theta, r1, color='blue', linewidth=2)
ax1.set_title('Polar: Rose Curve (r=|sin(3θ)|)')

# 右の図:アルキメデス螺線
r2 = theta / 6
ax2.plot(theta, r2, color='red', linewidth=2)
ax2.set_title('Polar: Archimedean Spiral')

plt.show()

よくある質問

squeeze パラメータは何に使うのか?

squeeze=True(デフォルト)の場合:subplots(1,1)返すax([ax] ではなく)、subplots(1,3)1次元配列を返します。

squeeze=False(squeeze=False)の場合は常に2次元配列を返します(行数・列数に関わらず)。統一処理が必要なシーンに適しています。

subplot_kw と gridspec_kw の違いは?

subplot_kw各 Axes 作成関数に渡します。例:projection='polar'。

gridspec_kwGridSpec レイアウトマネージャーに渡します。例:hspace=0.4(サブプロットの垂直間隔)。


Matplotlib リファレンスドキュメント

その他の拡張