I have several matplolib.pyplot figures. Each has a legend, and what I want is that clicking the line on the legend hides the line in the figure. The click event handling was found here: https://matplotlib.org/examples/event_handling/legend_picking.html
This works fine when there is only one figure, but when there are more than one, it only works with the last figure. When I click on the legend of another figure, I get no exception or warning, but nothing happens.
Here is an example code which features this issue:
import matplotlib.pyplot as plt
import numpy as np
a = np.arange(0,10,1)
b = np.arange(0,20,2)
c = np.arange(0,5,.5)
d = np.arange(-1,9,1)
lined = {}
for var1, var2 in [(a,b), (c,d)]:
fig, ax = plt.subplots()
line1, = ax.plot(var1, label="l1")
line2, = ax.plot(var2, label="l2")
leg = fig.legend([line1, line2], ["l1", "l2"])
legl1, legl2 = leg.get_lines()
legl1.set_picker(5)
lined[legl1] = line1
legl2.set_picker(5)
lined[legl2] = line2
def onpick(event, figu):
legl = event.artist
origl = lined[legl]
vis = not origl.get_visible()
origl.set_visible(vis)
if vis:
legl.set_alpha(1.0)
else:
legl.set_alpha(0.2)
figu.canvas.draw()
fig.canvas.mpl_connect('pick_event', lambda ev: onpick(ev, fig))
plt.show()
How can I make the click event work on the first figure too?