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

Skip to content

Commit ef29e67

Browse files
committed
Make checkbuttons with all plotted lines with correct visibility automatically
Previously you had to manually change the variables in func. Now it's done automatically based on the properties of the lines.
1 parent f859b74 commit ef29e67

1 file changed

Lines changed: 11 additions & 11 deletions

File tree

examples/widgets/check_buttons.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,23 @@
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-
rax = plt.axes([0.05, 0.4, 0.1, 0.15])
17-
check = CheckButtons(rax, ('2 Hz', '4 Hz', '6 Hz'), (False, True, True))
16+
lines = ax.get_lines()
1817

18+
# Make checkbuttons with all plotted lines with correct visibility
19+
rax = plt.axes([0.05, 0.4, 0.1, 0.15])
20+
labels = [str(graph.get_label()) for graph in lines]
21+
visibility = [graph.get_visible() for graph in lines]
22+
check = CheckButtons(rax, labels, visibility)
1923

2024
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())
25+
lines[labels.index(label)].set_visible(not lines[labels.index(label)].get_visible())
2726
plt.draw()
27+
2828
check.on_clicked(func)
2929

3030
plt.show()

0 commit comments

Comments
 (0)