Pyqtgraph类:如何从数据缓冲区自动更新图形值?

2024-07-01 07:07:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pyqtgraph模块来制作一个漂亮而简单的实时图形。我想把它作为一个类/对象来接收数据缓冲区,在更新时,重新读取数据缓冲区来绘制图形。我在从类代码外部获取数据缓冲区值到对象时遇到了一些问题。在

代码如下:

import pyqtgraph as pg
# pip install pyqtgraph


class App(QtGui.QMainWindow):
    def __init__(self, buffer_size, data_buffer, graph_title, parent=None):
        super(App, self).__init__(parent)

        #### Create Gui Elements ###########
        self.mainbox = QtGui.QWidget()
        self.setCentralWidget(self.mainbox)
        self.mainbox.setLayout(QtGui.QVBoxLayout())

        self.canvas = pg.GraphicsLayoutWidget()
        self.mainbox.layout().addWidget(self.canvas)

        self.label = QtGui.QLabel()
        self.mainbox.layout().addWidget(self.label)

        self.view = self.canvas.addViewBox()
        self.view.setAspectLocked(True)
        self.view.setRange(QtCore.QRectF(0,0, 100, 100))

        self.numDstreams = 1
        self.bufferLength = buffer_size
        self.dataBuffer = data_buffer
        self.graphTitle = graph_title

        self.otherplot = [[self.canvas.addPlot(row=i,col=0, title=self.graphTitle)] # , repeat line for more
                           for i in range(0,self.numDstreams)]
        self.h2 = [[self.otherplot[i][0].plot(pen='r')] for i in range(0,self.numDstreams)] # , self.otherplot[i][1].plot(pen='g'), self.otherplot[i][2].plot(pen='b')
        self.ydata = [[np.zeros((1,self.bufferLength))] for i in range(0,self.numDstreams)] # ,np.zeros((1,self.bufferLength)),np.zeros((1,self.bufferLength))

        for i in range(0,self.numDstreams):
            self.otherplot[i][0].setYRange(min= -100, max= 100) 

        self.counter = 0
        self.fps = 0.
        self.lastupdate = time.time()

        #### Start  #####################
        self._update()

    def _update(self):


        for i in range(0,self.numDstreams):
            self.ydata[i][0] = np.array(self.dataBuffer)

            self.h2[i][0].setData(self.ydata[i][0])


        now = time.time()
        dt = (now-self.lastupdate)
        if dt <= 0:
            dt = 0.000000000001
        fps2 = 1.0 / dt
        self.lastupdate = now
        self.fps = self.fps * 0.9 + fps2 * 0.1
        tx = 'Mean Frame Rate:  {fps:.3f} FPS'.format(fps=self.fps )
        self.label.setText(tx)
        QtCore.QTimer.singleShot(1, self._update)
        self.counter += 1


def CreateGraph(buffer_size, data_buffer, graph_title): 

    app1 = QtGui.QApplication(sys.argv)
    thisapp1 = App(buffer_size, data_buffer, graph_title)
    thisapp1.show()

    sys.exit(app1.exec_())
    return app1

if __name__ == "__main__":

    test_buffer = np.random.randn(100,)

    app = CreateGraph(100, test_buffer, "Activity Score")

    while 1:
        test_buffer = np.random.randn(100,)
        app._update()

代码的工作原理是,它绘制随机数据的初始图形。但是,它并没有像我希望的那样在循环中更新。当我使用这个对象时,我希望它根据一个外部变量更新它的图形数据缓冲区,就像我正在尝试的那样。相反,它是堆叠的,也就是说,它只读取第一次的数据。在

编辑-为了清楚起见,我希望test_buffer = np.random.randn(100,) app._update()在循环中不断更新图形。我需要图形能够实时读取缓冲区变量并绘制新数据。在

有什么办法吗?谢谢。在


Tags: inself图形fortitlebuffernpupdate
1条回答
网友
1楼 · 发布于 2024-07-01 07:07:45

在注释中,指出您的计算不正确,因此我将从我的答案中删除_update()方法。在

说到这一点,exec_()方法创建了一个whiletrue的事件循环,这样在该行之后就没有其他代码行被执行了,因此来自{}的代码永远不会被执行。在

另一方面,如果我们消除它,我们就不能将while 1:放在GUI线程中,因为它会阻止它,并且不会让GUI检查各种事件或更新GUI,例如绘画任务。在

另外,如果您使用test_buffer = np.random.randn(100,),这并不意味着self.dataBuffer已更新,则它们不会被链接。在

解决方案是将while 1:放入一个新线程中,并通过信号将数据发送到主线程。在

import sys

import threading

import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg


class App(QtGui.QMainWindow):
    def __init__(self, buffer_size=0, data_buffer=[], graph_title="", parent=None):
        super(App, self).__init__(parent)

        #### Create Gui Elements ###########
        self.mainbox = QtGui.QWidget()
        self.setCentralWidget(self.mainbox)
        self.mainbox.setLayout(QtGui.QVBoxLayout())

        self.canvas = pg.GraphicsLayoutWidget()
        self.mainbox.layout().addWidget(self.canvas)

        self.label = QtGui.QLabel()
        self.mainbox.layout().addWidget(self.label)

        self.view = self.canvas.addViewBox()
        self.view.setAspectLocked(True)
        self.view.setRange(QtCore.QRectF(0,0, 100, 100))

        self.numDstreams = 1
        self.bufferLength = buffer_size
        self.graphTitle = graph_title

        self.otherplot = [[self.canvas.addPlot(row=i,col=0, title=self.graphTitle)] # , repeat line for more
                           for i in range(0,self.numDstreams)]
        self.h2 = [[self.otherplot[i][0].plot(pen='r')] for i in range(0,self.numDstreams)] # , self.otherplot[i][1].plot(pen='g'), self.otherplot[i][2].plot(pen='b')
        self.ydata = [[np.zeros((1,self.bufferLength))] for i in range(0,self.numDstreams)] # ,np.zeros((1,self.bufferLength)),np.zeros((1,self.bufferLength))

        for i in range(0,self.numDstreams):
            self.otherplot[i][0].setYRange(min= -100, max= 100) 
        self.update_plot(data_buffer)

    def update_plot(self, data):
        self.dataBuffer = data
        for i in range(0, self.numDstreams):
            self.ydata[i][0] = np.array(self.dataBuffer)
            self.h2[i][0].setData(self.ydata[i][0])


def CreateGraph(graph_title): 
    thisapp1 = App(graph_title=graph_title)
    thisapp1.show()
    return thisapp1

class Helper(QtCore.QObject):
    bufferChanged = QtCore.pyqtSignal(object)

def generate_buffer(helper):
    while 1:
        test_buffer = np.random.randn(100,)
        helper.bufferChanged.emit(test_buffer)
        QtCore.QThread.msleep(1)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    graph = CreateGraph("Activity Score")
    helper = Helper()
    threading.Thread(target=generate_buffer, args=(helper, ), daemon=True).start()
    helper.bufferChanged.connect(graph.update_plot)

    if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'):
        sys.exit(app.exec_())

相关问题 更多 >

    热门问题