如何从情节中获取所有传说? 我有一个有2个或更多传说的情节。 我如何“让”所有传说改变(例如)传奇中的颜色和线性? 手柄,标签= ax.get_legend_handles_labels()只给了我...

问题描述 投票:0回答:2
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)]
python matplotlib plot
2个回答
13
投票
但这根本可以起作用吗?如果我添加更多像您提到的传奇人物,我会看到多个孩子,但所有这些都指向相同的对象。

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>]

配置:

8
投票
legends = ax.get_legend()

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.