I have created a line graph of some data in matplotlib. However, there are many observations, and so it is difficult to identify the trajectory of any single observation, as the graph is crowded.
I would like to add a picker function to the legend which, when a certain line is selected, would set the alpha of all other lines to 0, rendering them invisible. When selected again, alpha of other lines would assume their original values.
In order to do this, I have adapted code from this example:
http://matplotlib.org/1.4.3/examples/event_handling/legend_picking.html
I have followed this example to the best of my knowledge, but the graph is not responding as expected: the picker function is never executing. I have tried giving it more radius, and tried some slight variations in syntax, but I cannot identify the problem. Please find below the pertinent code:
#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)
Subsequently, I define a picker function 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)
And then attach it:
fig.canvas.draw()
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
I would appreciate any assistance you can offer me. Thank you in advance for your time.