|
8 | 8 | s2 = np.sin(6*np.pi*t) |
9 | 9 |
|
10 | 10 | 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') |
14 | 14 | plt.subplots_adjust(left=0.2) |
15 | 15 |
|
| 16 | +lines = ax.get_lines() |
| 17 | + |
| 18 | +# Make checkbuttons with all plotted lines with correct visibility |
16 | 19 | 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) |
18 | 23 |
|
19 | 24 |
|
20 | 25 | 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()) |
27 | 28 | plt.draw() |
| 29 | + |
28 | 30 | check.on_clicked(func) |
29 | 31 |
|
30 | 32 | plt.show() |
0 commit comments