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

yipeiwu_com6年前Python基础

我就废话不多说了,直接上代码吧!

from time import sleep
from threading importThread
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets importButton
fig, ax = plt.subplots()
#设置图形显示位置
plt.subplots_adjust(bottom=0.2)
#实验数据
range_start, range_end, range_step =0,1,0.005
t = np.arange(range_start, range_end, range_step)
s = np.sin(4*np.pi*t)
l,= plt.plot(t, s, lw=2)
#自定义类,用来封装两个按钮的单击事件处理函数
classButtonHandler:
def __init__(self):
self.flag =True
self.range_s, self.range_e, self.range_step =0,1,0.005
#线程函数,用来更新数据并重新绘制图形
def threadStart(self):
while self.flag:
sleep(0.02)
self.range_s += self.range_step
self.range_e += self.range_step
t = np.arange(self.range_s, self.range_e, self.range_step)
ydata = np.sin(4*np.pi*t)
#更新数据
l.set_xdata(t-t[0])
l.set_ydata(ydata)
#重新绘制图形
plt.draw()
defStart(self, event):
self.flag =True
#创建并启动新线程
t =Thread(target=self.threadStart)
t.start()
defStop(self, event):
self.flag =False
callback =ButtonHandler()
#创建按钮并设置单击事件处理函数
axprev = plt.axes([0.81,0.05,0.1,0.075])
bprev =Button(axprev,'Stop')
bprev.on_clicked(callback.Stop)
axnext = plt.axes([0.7,0.05,0.1,0.075])
bnext =Button(axnext,'Start')
bnext.on_clicked(callback.Start)
plt.show()

二 运行结果

以上这篇利用matplotlib实现根据实时数据动态更新图形就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解决Python下imread,imwrite不支持中文的问题

由以下函数代替该功能: def cv_imread(file_path): cv_img=cv2.imdecode(np.fromfile(file_path,dtype=np.u...

pytorch torch.nn.AdaptiveAvgPool2d()自适应平均池化函数详解

如题:只需要给定输出特征图的大小就好,其中通道数前后不发生变化。具体如下: AdaptiveAvgPool2d CLASStorch.nn.AdaptiveAvgPool2d(outp...

python 二分查找和快速排序实例详解

思想简单,细节颇多;本以为很简单的两个小程序,写起来发现bug频出,留此纪念。 #usr/bin/env python def binary_search(lst,t): low...

详解如何设置Python环境变量?

详解如何设置Python环境变量?

家好,我是Yivies!相信大家多多少少遇到过这样的情况吧?就是在安装了python之后想完整在命令提示符直接输入python就可以使用的操作,但是会出现输入了python之后找不到命令...

python读取txt文件,去掉空格计算每行长度的方法

如下所示: # -*- coding: utf-8 -*- file2 = open("source.txt", 'r') file1 = open("target.txt",...