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

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()
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()
for ax in fig.axes:
axLine, axLabel = ax.get_legend_handles_labels()
lines.extend(axLine)
labels.extend(axLabel)
単一の 1つのサブプロットにさらにラインとラベルが存在する場合に備えて、すべてのラインハンドルとラベルがリスト extend
メソッドを使用して lines
および labels
リストに追加されます。
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn