matplotlib实现根据实时数据动态更新图形

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

一 代码

  1. from time import sleep
  2. from threading importThread
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. from matplotlib.widgets importButton
  6. fig, ax = plt.subplots()
  7. #设置图形显示位置
  8. plt.subplots_adjust(bottom=0.2)
  9. #实验数据
  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()

二 运行结果

点这里可以跳转到人工智能网站