8000 When legend is outside the axes, pick events get handled twice · Issue #1962 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content
When legend is outside the axes, pick events get handled twice #1962
Closed
@dharadave

Description

@dharadave

Pick events on legends work perfectly unless the legend is moved out of the axes using bbox_to_anchor. After that, the pick event gets called twice for a single mouse click.

The following code demonstrates the error. The bug appears when the legend line is clicked: the line toggles twice on a mouse click instead of once.

''' 
Toggle plot line-styles between ':' and '-' when line is clicked or 
when the corresponding legend line is clicked.
'''
import pylab
import numpy

# Create data for plotting
t = numpy.linspace(0, 1.0, 100) 
a = numpy.sin(2*numpy.pi*t)

# Set up figure
fig = pylab.figure()
ax = pylab.subplot(111)

# Plot figures    
lines = []    
for i in range(5):
    line = ax.plot(t, (i+1)*a, linestyle=':', picker=5, label='line%d'%(i+1)) 
    lines.append(line[0]) # Save plot lines

# Create legend
leg = ax.legend(bbox_to_anchor=(1.01, 1), loc=2) # Does not work as expected
# leg = ax.legend() # Works!!

# Get legend lines
leglines = leg.get_lines() 
# Set event for legend lines
for line in leglines:
    line.set_picker(5)

# Create a 2 way mapping between legend lines <-> plot lines    
line2leg = dict(zip(lines+leglines, leglines+lines))

# Define event function
def onpick(event):
    thisline = event.artist

    if thisline.get_linestyle()==':':
        print ": -> -" # For debugging
        thisline.set_linestyle('-')
        line2leg[thisline].set_linestyle('-')
    else:
        print "- -> :" # For debugging
        thisline.set_linestyle(':')
        line2leg[thisline].set_linestyle(':')
    fig.canvas.draw()

# connect event function    
fig.canvas.mpl_connect('pick_event', onpick)
pylab.show()

(See also: http://stackoverflow.com/questions/16278358/double-event-registered-on-mouse-click-if-legend-is-outside-axes)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0