HOWTO · Matplotlib

Matplotlib のすべてのサブプロットに単一の凡例を作成する方法

Matplotlib の図クラスには、凡例を図レベルに配置するための凡例メソッドがありますが、サブプロットレベルにはありません。ラインのパターンとラベルがすべてのサブプロットで同じである場合に特に便利です。

このページの内容

Matplotlib figure クラスには、legend メソッドを figure レベルに配置するが、subplot レベルには配置しない legend メソッドがあります。ラインのパターンとラベルがすべてのサブプロットで同じである場合に特に便利です。

Matplotlib の figure.legend メソッドですべてのサブプロットの単一の凡例を作成する

import matplotlib.pyplot as plt

fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)

for ax in fig.axes:
    ax.plot([0, 10], [0, 10], label="linear")

lines, labels = fig.axes[-1].get_legend_handles_labels()

fig.legend(lines, labels, loc="upper center")

plt.show()

Matplotlib 図の凡例は凡例ハンドルラベルを取得する

lines, labels = fig.axes[-1].get_legend_handles_labels()

すべてのサブプロットが同じラインとラベルを持っていると仮定しているため、最後の Axes のハンドルとラベルを Figure 全体に使用できます。

Matplotlib でラインハンドルとラインが異なる場合、figure.legend メソッドを使用してすべてのサブプロットの単一の凡例を作成する

ラインパターンとラベルがサブプロット間で異なるが、すべてのサブプロットに 1つの凡例が必要な場合、すべてのサブプロットからすべてのラインハンドルとラベルを取得する必要があります。

import matplotlib.pyplot as plt
import numpy as np

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

fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)

axes[0, 0].plot(x, np.sin(x), color="k", label="sin(x)")
axes[0, 1].plot(x, np.cos(x), color="b", label="cos(x)")
axes[1, 0].plot(x, np.sin(x) + np.cos(x), color="r", label="sin(x)+cos(x)")
axes[1, 1].plot(x, np.sin(x) - np.cos(x), color="m", label="sin(x)-cos(x)")

lines = []
labels = []

for ax in fig.axes:
    axLine, axLabel = ax.get_legend_handles_labels()
    lines.extend(axLine)
    labels.extend(axLabel)


fig.legend(lines, labels, loc="upper right")

plt.show()

get_legend_handles_labels からの Matplotlib 図 Legend_all ラベル

for ax in fig.axes:
    axLine, axLabel = ax.get_legend_handles_labels()
    lines.extend(axLine)
    labels.extend(axLabel)

単一の 1つのサブプロットにさらにラインとラベルが存在する場合に備えて、すべてのラインハンドルとラベルがリスト extend メソッドを使用して lines および labels リストに追加されます。