Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2521750

Browse files
authored
Merge pull request #27206 from meeseeksmachine/auto-backport-of-pr-27205-on-v3.8.x
Backport PR #27205 on branch v3.8.x (Improve legend picking example)
2 parents cf6ffe6 + b0859e6 commit 2521750

File tree

1 file changed

+26
-13
lines changed

1 file changed

+26
-13
lines changed

galleries/examples/event_handling/legend_picking.py

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,33 +18,46 @@
1818
import numpy as np
1919

2020
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)
2323

2424
fig, ax = plt.subplots()
2525
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')
2828
leg = ax.legend(fancybox=True, shadow=True)
2929

3030
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
3538

3639

3740
def on_pick(event):
3841
# On the pick event, find the original line corresponding to the legend
3942
# 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)
4452
# Change the alpha on the line in the legend, so we can see what lines
4553
# 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)
4755
fig.canvas.draw()
4856

57+
4958
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+
5063
plt.show()

0 commit comments

Comments
 (0)