handles, labels = ax.get_legend_handles_labels()
只给了我“第一个”传奇,我用
plt.legend()
添加到了图中。但是我也想要其他传奇人物,我添加了
plt.gca().add_artist(leg2)
我该怎么办?
您可以从轴上让所有孩子都从轴上滤波,并在传说类型上过滤:
legends = [c for c in ax.get_children() if isinstance(c, mpl.legend.Legend)]
Edit:
轴本身会添加最后一个传奇,因此,如果您添加了上一个传奇,则会看到多个不同的传说:
例如:
Legend
返回这些对象:
.add_artist()
这是否是您想做的事情还有待观察!您还可以与轴分开存储线条(或其他类型)。
solution替代方案:
fig, ax = plt.subplots()
l1, = ax.plot(x,y, 'k', label='l1')
leg1 = plt.legend([l1],['l1'])
l2, = ax.plot(x,y, 'k', label='l2')
leg2 = plt.legend([l2],['l2'])
ax.add_artist(leg1)
print(ax.get_children())
访问传说的属性:
[<matplotlib.axis.XAxis at 0xd0e6eb8>,
<matplotlib.axis.YAxis at 0xd0ff7b8>,
<matplotlib.lines.Line2D at 0xd0f73c8>,
<matplotlib.lines.Line2D at 0xd5c1a58>,
<matplotlib.legend.Legend at 0xd5c1860>,
<matplotlib.legend.Legend at 0xd5c4b70>,
<matplotlib.text.Text at 0xd5b1dd8>,
<matplotlib.text.Text at 0xd5b1e10>,
<matplotlib.text.Text at 0xd5b1e48>,
<matplotlib.patches.Rectangle at 0xd5b1e80>,
<matplotlib.spines.Spine at 0xd0e6da0>,
<matplotlib.spines.Spine at 0xd0e6ba8>,
<matplotlib.spines.Spine at 0xd0e6208>,
<matplotlib.spines.Spine at 0xd0f10f0>]
配置:
legends = ax.get_legend()