---
title: "matplotlib实现根据实时数据动态更新图形"
author: "cakin24"
date: "2017-08-01T21:45:16Z"
tags: []
categories: ["编程语言"]
slug: "matplotlib"
draft: false
lastmod: "2017-08-01T21:45:16Z"
id: 2387970
url: "https://cakin24.iteye.com/blog/2387970"
---

**一 代码**

01. `from time import sleep`
02. `from threading importThread`
03. `import numpy as np`
04. `import matplotlib.pyplot as plt`
05. `from matplotlib.widgets importButton`
06. `fig, ax = plt.subplots()`
07. `#设置图形显示位置`
08. `plt.subplots_adjust(bottom=0.2)`
09. `#实验数据`
10. `range_start, range_end, range_step =0,1,0.005`
11. `t = np.arange(range_start, range_end, range_step)`
12. `s = np.sin(4*np.pi*t)`
13. `l,= plt.plot(t, s, lw=2)`
14. `#自定义类，用来封装两个按钮的单击事件处理函数`
15. `classButtonHandler:`
16. `def __init__(self):`
17. `self.flag =True`
18. `self.range_s, self.range_e, self.range_step =0,1,0.005`
19. `#线程函数，用来更新数据并重新绘制图形`
20. `def threadStart(self):`
21. `while self.flag:`
22. `sleep(0.02)`
23. `self.range_s += self.range_step`
24. `self.range_e += self.range_step`
25. `t = np.arange(self.range_s, self.range_e, self.range_step)`
26. `ydata = np.sin(4*np.pi*t)`
27. `#更新数据`
28. `l.set_xdata(t-t[0])`
29. `l.set_ydata(ydata)`
30. `#重新绘制图形`
31. `plt.draw()`
32. `defStart(self, event):`
33. `self.flag =True`
34. `#创建并启动新线程`
35. `t =Thread(target=self.threadStart)`
36. `t.start()`
37. `defStop(self, event):`
38. `self.flag =False`
39. `callback =ButtonHandler()`
40. `#创建按钮并设置单击事件处理函数`
41. `axprev = plt.axes([0.81,0.05,0.1,0.075])`
42. `bprev =Button(axprev,'Stop')`
43. `bprev.on_clicked(callback.Stop)`
44. `axnext = plt.axes([0.7,0.05,0.1,0.075])`
45. `bnext =Button(axnext,'Start')`
46. `bnext.on_clicked(callback.Start)`
47. `plt.show()`

**二 运行结果**

![](http://dl2.iteye.com/upload/attachment/0126/3617/ca961016-6140-3c74-bdfa-f3175efd7620.png)