Possible bug processing events outisde


On matplotlib’s home, there is a demo ( a program called legend_picking.py ) were one can click on the lines in the legend of a plot to hide / unhide the corresponding plot lines.

However there is a problem when the click takes place outside the main canvas (the white space).

I made a small project demonstrating the problem:

  1. Normally the legend should hold 2 lines: a red one on the top (it should be outside the canvas) and, below it a red line (it should be within the canvas). If this is not the case you may have to tweak the loc=(0,0.95) parameters to get to this situation.

  2. Click on the blue line. Everything is normal: the blue plot goes on and off on the canvas.

  3. Click on the red line. The event handler is called twice, hiding and unhiding the red plot (visible via the “print” statement in the function) This makes it impossible to hide the plot.

Thank you for reading,


The code follows:

import matplotlib.pyplot as plt


ax = fig.add_subplot(111)


p0,=plt.plot([0,1,2,3], ‘r’)

p1,=plt.plot([3,0,6,2], ‘b’)


#leg = ax.legend((‘Sausage length’, ‘Sauerkraut Vitamin content’, ‘Total message length’), ‘upper center’, shadow=True)

leg = ax.legend((‘Sausage length’, ‘Sauerkraut Vitamin content’, ‘Total message length’), loc=(0,0.95), shadow=True)

we will set up a dict mapping legend line to orig line, and enable

picking on the legend line

lines = [p0, p1]

lined = dict()

for legline, origline in zip(leg.get_lines(), lines):

legline.set_picker(5) # pts tolerance

lined[legline] = origline

def onpick(event):

print ‘in onpick’

on the pick event, find the orig line corresponding to the

legend proxy line, and toggle the visibilit

legline = event.artist

origline = lined[legline]

print ‘origline=’, origline

vis = not origline.get_visible()


print ‘vis=’, vis

Change the alpha on the line in the legend so we can see what lines

have been toggled

if vis:





fig.canvas.mpl_connect(‘pick_event’, onpick)