|
18 | 18 | import numpy as np
|
19 | 19 |
|
20 | 20 | t = np.linspace(0, 1)
|
21 |
| -y1 = 2 * np.sin(2*np.pi*t) |
22 |
| -y2 = 4 * np.sin(2*np.pi*2*t) |
| 21 | +y1 = 2 * np.sin(2 * np.pi * t) |
| 22 | +y2 = 4 * np.sin(2 * np.pi * 2 * t) |
23 | 23 |
|
24 | 24 | fig, ax = plt.subplots()
|
25 | 25 | ax.set_title('Click on legend line to toggle line on/off')
|
26 |
| -line1, = ax.plot(t, y1, lw=2, label='1 Hz') |
27 |
| -line2, = ax.plot(t, y2, lw=2, label='2 Hz') |
| 26 | +(line1, ) = ax.plot(t, y1, lw=2, label='1 Hz') |
| 27 | +(line2, ) = ax.plot(t, y2, lw=2, label='2 Hz') |
28 | 28 | leg = ax.legend(fancybox=True, shadow=True)
|
29 | 29 |
|
30 | 30 | lines = [line1, line2]
|
31 |
| -lined = {} # Will map legend lines to original lines. |
32 |
| -for legline, origline in zip(leg.get_lines(), lines): |
33 |
| - legline.set_picker(True) # Enable picking on the legend line. |
34 |
| - lined[legline] = origline |
| 31 | +map_legend_to_ax = {} # Will map legend lines to original lines. |
| 32 | + |
| 33 | +pickradius = 5 # Points (Pt). How close the click needs to be to trigger an event. |
| 34 | + |
| 35 | +for legend_line, ax_line in zip(leg.get_lines(), lines): |
| 36 | + legend_line.set_picker(pickradius) # Enable picking on the legend line. |
| 37 | + map_legend_to_ax[legend_line] = ax_line |
35 | 38 |
|
36 | 39 |
|
37 | 40 | def on_pick(event):
|
38 | 41 | # On the pick event, find the original line corresponding to the legend
|
39 | 42 | # proxy line, and toggle its visibility.
|
40 |
| - legline = event.artist |
41 |
| - origline = lined[legline] |
42 |
| - visible = not origline.get_visible() |
43 |
| - origline.set_visible(visible) |
| 43 | + legend_line = event.artist |
| 44 | + |
| 45 | + # Do nothing if the source of the event is not a legend line. |
| 46 | + if legend_line not in map_legend_to_ax: |
| 47 | + return |
| 48 | + |
| 49 | + ax_line = map_legend_to_ax[legend_line] |
| 50 | + visible = not ax_line.get_visible() |
| 51 | + ax_line.set_visible(visible) |
44 | 52 | # Change the alpha on the line in the legend, so we can see what lines
|
45 | 53 | # have been toggled.
|
46 |
| - legline.set_alpha(1.0 if visible else 0.2) |
| 54 | + legend_line.set_alpha(1.0 if visible else 0.2) |
47 | 55 | fig.canvas.draw()
|
48 | 56 |
|
| 57 | + |
49 | 58 | fig.canvas.mpl_connect('pick_event', on_pick)
|
| 59 | + |
| 60 | +# Works even if the legend is draggable. This is independent from picking legend lines. |
| 61 | +leg.set_draggable(True) |
| 62 | + |
50 | 63 | plt.show()
|
0 commit comments