介绍
使用matplotlib怎么实现一个数据实时刷新功能?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
import matplotlib.pyplot as plt import numpy  as np import 线程 import 系统 得到random import 随机的,randrange 得到time import 睡眠 & # 39;& # 39;& # 39; 绘制2 x2的画板 可设置窗口标题和4个子图标题 可更新曲线数据 & # 39;& # 39;& # 39; #=quit_flag False 退出标志 class Plot2_2(对象): “““才能,2 x2的画板,“““ def __init__(才能自我,,wtitle=& # 39;图# 39;,,p1title=& # 39; 1 & # 39;,, p2title=& # 39; 2 & # 39;,, p3title=& # 39; 3 & # 39;, ,,,,,,,,p4title=& # 39; 4 & # 39;): ,,,self.sub_title =, (p2title, p1title,还以为,p3title, p4title), #, 4个子图的标题 ,,,,,,self.fig self.ax =, plt.subplots(2, 2), #,创建2 x2子图 ,,,self.fig.subplots_adjust (wspace=0.3,水平间距=0.3),#,设置子图之间的间距 ,,,self.fig.canvas.set_window_title (wtitle), #,设置窗口标题 ,,,#,子图字典,关键为子图的序号,值为子图句柄 ,,,self.axdict =, {0: self.ax (0, 0), 1:, self.ax [0, 1], 2:, self.ax (1, 0), 3:, self.ax (1, 1)} def 才能showPlot(自我): ,,,,,,,显示曲线,“““ ,,,plt.show () def 才能setPlotStyle(自我,,指数): ,,,,,,,设置子图的样式,这里仅设置了标题,“““ ,,,self.axdict(指数).set_title (self.sub_title(指数),字形大?12) def 才能;updatePlot(自我,,指数,x,, y): ,,,,,, ,,,更新指定序号的子图 ,,,:param 指数:,子图序号 ,,,:param x:,横轴数据 ,,,:param y:,纵轴数据 ,,,:返回: ,,,,,, ,,,#,X轴数据必须和Y轴数据长度一致 ,,,if len (x), !=, len (y): ,,,,,ex =, ValueError (“x 以及y must have same first dimension") ,,,,,raise 交货 ,,,self.axdict(指数).cla(), #,清空子图数据 ,,,self.axdict(指数).plot (x, y), #,绘制最新的数据 ,,,self.setPlotStyle(索引),#,设置子图样式 ,,,if min (x), & lt;,马克斯(x): ,,,,,self.axdict(指数).set_xlim (min (x), max (x)), #,根据x轴数据区间调整x轴范围 ,,,plt.draw () ,,,print (“% s 以何种,%,sys._getframe () .f_code.co_name) def updatePlot(图): “才能”;“ 模才能拟收到实时数据,更新曲线的操作 :才能param 情节:,曲线实例 ,,:返回: “才能”;“ 打印才能(“线程:% s", %, threading.current_thread () . getname ()) count 才能=0 global quit_flag才能 打印才能(“quit_flag (% s)“, %, str (quit_flag)) while 才能正确的: ,,,if quit_flag: ,,,,,印刷(“quit_flag (% s)“, %, str (quit_flag)) ,,,,,休息 ,,,count +=1 ,,,print(“数# % d", %,计数) ,,,x =, np.arange (100 0,,,, 1) ,,,y =, np.random.normal (loc=1,,=1,规模,大?100),#,产生随机数、模拟变化的曲线 ,,,index =, randrange(4), #,随机更新某一个子图 ,,,plot.updatePlot(指数,x,, y) ,,,睡眠(随机(),*,3) def main (): 时间=p 才能;Plot2_2(), #,创建一个2 x2画板 t 才能=,threading.Thread(目标=updatePlot, arg游戏=(p)), #,启动一个线程更新曲线数据 t.start才能() p.showPlot才能(),#,showPlot方法会阻塞当前线程,直到窗口关闭 打印才能(“plot close") global quit_flag才能 时间=quit_flag 才能;True #,通知更新曲线数据的线程退出 t.join才能() 打印才能(“线程:% s 以何种;,%,threading.current_thread () . getname ()) if __name__ ==, & # 39; __main__ # 39;: 以前,,main () >使用matplotlib怎么实现一个数据实时刷新功能