复选按钮

使用复选按钮打开和关闭视觉元素。

该程序显示了“检查按钮”的使用,类似于复选框。 显示了3种不同的正弦波,我们可以选择使用复选按钮显示哪些波形。

复选按钮示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.widgets import CheckButtons
  4. t = np.arange(0.0, 2.0, 0.01)
  5. s0 = np.sin(2*np.pi*t)
  6. s1 = np.sin(4*np.pi*t)
  7. s2 = np.sin(6*np.pi*t)
  8. fig, ax = plt.subplots()
  9. l0, = ax.plot(t, s0, visible=False, lw=2, color='k', label='2 Hz')
  10. l1, = ax.plot(t, s1, lw=2, color='r', label='4 Hz')
  11. l2, = ax.plot(t, s2, lw=2, color='g', label='6 Hz')
  12. plt.subplots_adjust(left=0.2)
  13. lines = [l0, l1, l2]
  14. # Make checkbuttons with all plotted lines with correct visibility
  15. rax = plt.axes([0.05, 0.4, 0.1, 0.15])
  16. labels = [str(line.get_label()) for line in lines]
  17. visibility = [line.get_visible() for line in lines]
  18. check = CheckButtons(rax, labels, visibility)
  19. def func(label):
  20. index = labels.index(label)
  21. lines[index].set_visible(not lines[index].get_visible())
  22. plt.draw()
  23. check.on_clicked(func)
  24. plt.show()

下载这个示例