Matplotlib 中如何为所有子图创建一个图例

Matplotlib figure 类中的 legend 方法,用于将 legend 放置在图形级别而不是 subplot 级别。如果所有子图中线条的图案和标签都相同,则用起来会特别方便。

在 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 的句柄和标签可以用于整个图形。

当 Matplotlib 中的线柄和线不同时,使用 figure.legend 方法为所有子图制作单个图例

如果子图之间的线型和标签不同,但是所有子图都需要一个图例,则需要从所有子图中获取所有的线柄和标签。

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()

Matplotlib 中如何为所有子图创建一个图例

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

万一单个子图中存在更多的行和标签,所有的线条句柄和标签都将通过列表 extend 方法添加到 lineslabels 列表中。