Skip to content

Commit 3ba65f1

Browse files
authored
Merge pull request #6310 from BTWS/patch-1
Make checkbuttons with all plotted lines with correct visibility automatically
2 parents d9507a2 + 0ee87e6 commit 3ba65f1

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

examples/widgets/check_buttons.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,25 @@
88
s2 = np.sin(6*np.pi*t)
99

1010
fig, ax = plt.subplots()
11-
l0, = ax.plot(t, s0, visible=False, lw=2)
12-
l1, = ax.plot(t, s1, lw=2)
13-
l2, = ax.plot(t, s2, lw=2)
11+
ax.plot(t, s0, visible=False, lw=2, color='k', label='2 Hz')
12+
ax.plot(t, s1, lw=2, color='r', label='4 Hz')
13+
ax.plot(t, s2, lw=2, color='g', label='6 Hz')
1414
plt.subplots_adjust(left=0.2)
1515

16+
lines = ax.get_lines()
17+
18+
# Make checkbuttons with all plotted lines with correct visibility
1619
rax = plt.axes([0.05, 0.4, 0.1, 0.15])
17-
check = CheckButtons(rax, ('2 Hz', '4 Hz', '6 Hz'), (False, True, True))
20+
labels = [str(line.get_label()) for line in lines]
21+
visibility = [line.get_visible() for line in lines]
22+
check = CheckButtons(rax, labels, visibility)
1823

1924

2025
def func(label):
21-
if label == '2 Hz':
22-
l0.set_visible(not l0.get_visible())
23-
elif label == '4 Hz':
24-
l1.set_visible(not l1.get_visible())
25-
elif label == '6 Hz':
26-
l2.set_visible(not l2.get_visible())
26+
index = labels.index(label)
27+
lines[index].set_visible(not lines[index].get_visible())
2728
plt.draw()
29+
2830
check.on_clicked(func)
2931

3032
plt.show()

0 commit comments

Comments
 (0)