在matplotlib.pyplot中为图例设置项目选择器

时间:2015-05-20 21:45:57

标签: python matplotlib

我在matplotlib中创建了一些数据的折线图。然而,有许多观测结果,因此很难确定任何单一观测的轨迹,因为图形很拥挤。

我想在图例中添加一个选择器功能,当选择某条线时,会将所有其他线的alpha设置为0,使它们不可见。再次选择时,其他行的alpha将采用其原始值。

为了做到这一点,我改编了这个例子中的代码:
http://matplotlib.org/1.4.3/examples/event_handling/legend_picking.html

据我所知,我已经按照这个例子,但图表没有按预期响应:选择器功能永远不会执行。我试过给它更多的半径,并尝试了一些语法上的微小变化,但我无法确定问题。请在下面找到相关代码:

#initialize figure
fig, axp = plt.subplots()

#plotting, one by one.
lines = [x for x in range(0, len(df.columns))]
for i, country in enumerate(df):
    lines[i],  = axp.plot(range(0, len(df[country]-1)), df[country], label = country)

#create legend
leg = axp.legend(loc='upper right', fancybox=True, shadow=True)

#fixing plot size to fit key
box = axp.get_position()
axp.set_position([box.x0, box.y0, box.width * 0.8, box.height])

#fixing key location and size
axp.legend(loc='center left', bbox_to_anchor=(1, 0.5),prop={'size':10})

#create dictionary for picking, set picking radius
lined = dict()
for legline, origline in zip(leg.get_lines(), lines):
    lined[legline] = origline
    legline.set_picker(5)

随后,我定义了一个选择器函数onpick:

def onpick(artist, event):
    # on the pick event, find the orig line corresponding to the
    # legend proxy line, and toggle the visibility
    print 'This function is being executed'
    origline = lined[artist]
    vis = not origline.get_visible()
    origline.set_visible(vis)
    # Change the alpha on the line in the legend so we can see what lines
    # have been toggled
    if vis:
        artist.set_alpha(1.0)
    else:
        artist.set_alpha(0.2)

然后附上它:

fig.canvas.draw()


fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

感谢您提供给我的任何帮助。提前感谢您的时间。

0 个答案:

没有答案