使用Slider组件调整曲线参数

一 代码

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.widgets importSlider,Button,RadioButtons
  4. fig, ax = plt.subplots()
  5. plt.subplots_adjust(left=0.1, bottom=0.25)
  6. t = np.arange(0.0,1.0,0.001)
  7. #初始振幅与频率,并绘制初始图形
  8. a0, f0=5,3
  9. s = a0*np.sin(2*np.pi*f0*t)
  10. l,= plt.plot(t, s, lw=2, color='red')
  11. #设置坐标轴刻度范围
  12. plt.axis([0,1,-10,10])
  13. axColor ='lightgoldenrodyellow'
  14. #创建两个Slider组件,分别设置位置/尺寸、背景色和初始值
  15. axfreq = plt.axes([0.1,0.1,0.75,0.03], axisbg=axColor)
  16. sfreq =Slider(axfreq,'Freq',0.1,30.0, valinit=f0)
  17. axamp = plt.axes([0.1,0.15,0.75,0.03], axisbg=axColor)
  18. samp =Slider(axamp,'Amp',0.1,10.0, valinit=a0)
  19. #为Slider组件设置事件处理函数
  20. def update(event):
  21. #获取Slider组件的当前值,并以此来更新图形
  22. amp = samp.val
  23. freq = sfreq.val
  24. l.set_ydata(amp*np.sin(2*np.pi*freq*t))
  25. plt.draw()
  26. #fig.canvas.draw_idle()
  27. sfreq.on_changed(update)
  28. samp.on_changed(update)
  29. def adjustSliderValue(event):
  30. ampValue = samp.val +0.05
  31. if ampValue >10:
  32. ampValue =0.1
  33. samp.set_val(ampValue)
  34. freqValue = sfreq.val +0.05
  35. if freqValue >30:
  36. freqValue =0.1
  37. sfreq.set_val(freqValue)
  38. update(event)
  39. axAdjust = plt.axes([0.6,0.025,0.1,0.04])
  40. buttonAdjust =Button(axAdjust,'Adjust', color=axColor, hovercolor='red')
  41. buttonAdjust.on_clicked(adjustSliderValue)
  42. #创建按钮组件,用来恢复初始值
  43. resetax = plt.axes([0.8,0.025,0.1,0.04])
  44. button =Button(resetax,'Reset', color=axColor, hovercolor='yellow')
  45. def reset(event):
  46. sfreq.reset()
  47. samp.reset()
  48. button.on_clicked(reset)
  49. ###用来控制图形颜色的
  50. ##rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axColor)
  51. ##radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
  52. ##def colorfunc(label):
  53. ## l.set_color(label)
  54. ## fig.canvas.draw_idle()
  55. ##radio.on_clicked(colorfunc)
  56. plt.show()
二 运行结果

 

猜你喜欢

转载自cakin24.iteye.com/blog/2388117