滑块演示

使用滑块小部件来控制绘图的可视属性。

在此示例中,滑块用于选择正弦波的频率。 您可以通过这种方式控制绘图的许多连续变化属性。

滑块演示

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.widgets import Slider, Button, RadioButtons
  4. fig, ax = plt.subplots()
  5. plt.subplots_adjust(left=0.25, bottom=0.25)
  6. t = np.arange(0.0, 1.0, 0.001)
  7. a0 = 5
  8. f0 = 3
  9. delta_f = 5.0
  10. s = a0*np.sin(2*np.pi*f0*t)
  11. l, = plt.plot(t, s, lw=2, color='red')
  12. plt.axis([0, 1, -10, 10])
  13. axcolor = 'lightgoldenrodyellow'
  14. axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
  15. axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
  16. sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0, valstep=delta_f)
  17. samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)
  18. def update(val):
  19. amp = samp.val
  20. freq = sfreq.val
  21. l.set_ydata(amp*np.sin(2*np.pi*freq*t))
  22. fig.canvas.draw_idle()
  23. sfreq.on_changed(update)
  24. samp.on_changed(update)
  25. resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
  26. button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
  27. def reset(event):
  28. sfreq.reset()
  29. samp.reset()
  30. button.on_clicked(reset)
  31. rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
  32. radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
  33. def colorfunc(label):
  34. l.set_color(label)
  35. fig.canvas.draw_idle()
  36. radio.on_clicked(colorfunc)
  37. plt.show()

下载这个示例