import pyqtgraph as pg import numpy as np from pyqtgraph.Qt import QtCore app = pg.QtGui.QApplication([]) win = pg.GraphicsWindow(title="动态更新数据") win.resize(600,300) #设置窗口大小 p = win.addPlot() data = np.random.random(size=50) curve = p.plot(data) #在坐标p中绘图并返回图形对象 def update(): global data, curve data[:-1] = data[1:] data[-1] = np.random.random() curve.setData(data) #给图形对象设置数据---图形对象重新绘图 timer = QtCore.QTimer() #创建一个定时器 timer.timeout.connect(update) #设置定时器执行函数 timer.start(100) #启动 #参数:间隔毫秒数 app.exec_()
上面的图形,数据更新后,横坐标并没有跟随新的数据做出改变,这里可以用setPos来实现
import pyqtgraph as pg import numpy as np from pyqtgraph.Qt import QtCore app = pg.QtGui.QApplication([]) win = pg.GraphicsWindow(title="动态更新数据") win.resize(600,300) p = win.addPlot() data = np.random.random(size=50) curve = p.plot(data) ptr=0 def update(): global data, curve,ptr data[:-1] = data[1:] data[-1] = np.random.random() curve.setData(data) ptr += 1 curve.setPos(ptr, 0) #给图形对象设置新的坐标值 #参数1:x轴起点坐标 #参数2:y轴起点坐标 timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(100) app.exec_()
p.setRange(xRange=[-100, 0]) # 将横坐标的范围限定为[-100,0] p.setLimits(xMax=0) # 横坐标的最大值为0