---
title: "使用Slider组件调整曲线参数"
author: "cakin24"
date: "2017-08-02T21:58:21Z"
tags: []
categories: ["编程语言"]
slug: "slider"
draft: false
lastmod: "2017-08-02T21:58:21Z"
id: 2388117
url: "https://cakin24.iteye.com/blog/2388117"
---

**一 代码**

01. `import numpy as np`
02. `import matplotlib.pyplot as plt`
03. `from matplotlib.widgets importSlider,Button,RadioButtons`
04. `fig, ax = plt.subplots()`
05. `plt.subplots_adjust(left=0.1, bottom=0.25)`
06. `t = np.arange(0.0,1.0,0.001)`
07. `#初始振幅与频率，并绘制初始图形`
08. `a0, f0=5,3`
09. `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()`

**二 运行结果**

![](http://dl2.iteye.com/upload/attachment/0126/3835/1a55ef82-d67d-3c14-9231-cdd4bbe1f2dd.png)