【发布时间】:2023-03-24 02:20:01
【问题描述】:
免责声明:我知道在这个简单的示例中使用子图无关紧要,后者仅用于说明我的问题:我希望能够将fig.legend() 与fig.subfigures1 一起使用。
我目前正在发现 matplotlib 的新 subfigure 模块。我注意到当主图包含子图时,使用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)
【问题讨论】:
标签: python matplotlib legend