Closed
Description
I am trying to create legend that can toggle the visibility of each drawn object. Here is my code. It works on the line legend, but clicking on the dot legend object doesn't toggle the drawn object. In contrast, clicking outside the dot legend object will toggle the drawn object. This is counter-intuitive from the use perspective. Does anyone has any workaround to this issue?
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
y = np.random.random(size=50)
x = np.random.choice(np.arange(len(y)), 10, replace=False)
line, = ax.plot(y, '-', label='line')
dot, = ax.plot(x, y[x], 'o', label='dot')
legend = ax.legend()
line_leg, dot_leg = legend.get_lines()
line_leg.set_picker(True)
line_leg.set_pickradius(5)
dot_leg.set_picker(True)
dot_leg.set_pickradius(5)
pickables = {}
pickables[line_leg] = line
pickables[dot_leg] = dot
def on_pick(event):
leg = event.artist
visible = leg.get_visible()
visible = not visible
pickables[leg].set_visible(visible)
leg.set_visible(visible)
fig.canvas.draw()
plt.connect('pick_event', on_pick)
plt.show()