Matplotlib 多个子图使用一个图例
情况1:所有的子图图例相同
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') # 图例的位置,bbox_to_anchor=(0.5, 0.92),
plt.show()
情况2:所有的子图图例不同
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') # 图例的位置,bbox_to_anchor=(0.5, 0.92),
plt.show()
情况3:子图图例不完全相同
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 = []
lines_01, labels_01 = fig.axes[2].get_legend_handles_labels()
lines.extend(lines_01); labels.extend(labels_01)
lines_02, labels_02 = fig.axes[3].get_legend_handles_labels()
lines.extend(lines_02); labels.extend(labels_02)
lines_03, labels_03 = fig.axes[-1].get_legend_handles_labels()
lines.extend(lines_03); labels.extend(labels_03)
fig.legend(lines, labels, loc = 'upper center') # 图例的位置,bbox_to_anchor=(0.5, 0.92),
plt.show()
部分代码参考 https://www.delftstack.com/zh/howto/matplotlib/how-to-make-a-single-legend-for-all-subplots-in-matplotlib/