我正在尝试编写一个与matplotlib errorbar图类似的图例选择器,类似于这个示例。我希望能够通过单击图例中的误差线/数据点来切换它们在轴上的可见性。问题是
plt.legend()
返回的图例对象不包含有关用于创建图例的艺术家的任何数据。例如,如果我执行以下操作:import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = np.linspace(0,10,100)
y = np.sin(x) + np.random.rand(100)
yerr = np.random.rand(100)
erbpl1 = ax.errorbar(x, y, yerr=yerr, fmt='o', label='A')
erbpl2 = ax.errorbar(x, 0.02*y, yerr=yerr, fmt='o', label='B')
leg = ax.legend()
从这里看来,通过使用leg
对象似乎无法访问图例的艺术家。通常,可以在更简单的图例中执行此操作,例如:
plt.plot(x, y, label='whatever')
leg = plt.legend()
proxy_lines = leg.get_lines()
该函数返回用于图例的Line2D对象。但是,在errorbar图中,leg.get_lines()
会返回一个空列表。这有点合理,因为plt.errorbar
返回一个matplotlib.container.ErrorbarContainer
对象(其中包含数据点、误差线端点和误差线)。我希望图例有一个类似的数据容器,但我找不到它。我能找到的最接近的是leg.legendHandles
,它指向误差线,但没有数据点或端点。如果您可以选择图例,您可以使用字典将其映射到原始图,并使用以下函数打开/关闭误差线。
def toggle_errorbars(erb_pl):
points, caps, bars = erb_pl
vis = bars[0].get_visible()
for line in caps:
line.set_visible(not vis)
for bar in bars:
bar.set_visible(not vis)
return vis
def onpick(event):
# on the pick event, find the orig line corresponding to the
# legend proxy line, and toggle the visibility
legline = event.artist
origline = lined[legline]
vis = toggle_errorbars(origline)
## Change the alpha on the line in the legend so we can see what lines
## have been toggled
if vis:
legline.set_alpha(.2)
else:
legline.set_alpha(1.)
fig.canvas.draw()
我的问题是,是否有一种解决方法可以让我在误差线/其他复杂图例上进行事件选择?