免责声明:我知道在这个简单的示例中使用子图是无关紧要的,后者仅用于显示我的问题:我希望能够使用fig.legend()
with fig.subfigures1
.
我目前正在探索新的子图 https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subfigures.htmlmatplotlib 的模块。我注意到使用创建的人物图例fig.legend()
当主图包含子图时不显示:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1, 10, 10)
y1 = x
y2 = -x
fig = plt.figure(constrained_layout=True)
subfigs = fig.subfigures(nrows=2, ncols=1)
for subfig in subfigs:
axarr = subfig.subplots(1, 2)
for ax in axarr.flatten():
l1, = ax.plot(x, y1, label='line1')
l2, = ax.plot(x, y2, label='line2')
#
ax.legend()
# subfig.legend(handles=[l1, l2], loc='upper center', ncol=2)
fig.legend(handles=[l1, l2], loc='upper center', ncol=2)
plt.savefig('subfigures_figlegend.png', dpi=200)
请注意该图例是如何缺失的。为了进行比较,请注意仅使用时显示plt.subplots
:
fig, axarr = plt.subplots(2, 2, constrained_layout=True)
for ax in axarr.flatten():
l1, = ax.plot(x, y1, label='line1')
l2, = ax.plot(x, y2, label='line2')
#
ax.legend()
fig.legend(handles=[l1, l2], loc='upper center', ncol=2)
plt.savefig('subplots_figlegend.png', dpi=200)