无法使用新数据点更新 Pyqtgraph 图

Unable to Update Pyqtgraph Plot with New Data Point

我正在制作我的第一个 pyqtgraph 图,它将被添加到 Pyqt GUI 中。按下按钮 addBtn 时,应将新数据点添加到 pyqtgraph 图中。

问题:使用setData函数将新的x和y数据添加为np.array对象returns错误:

TypeError: setData(self, int, QVariant): argument 1 has unexpected type 'numpy.ndarray'

我们如何解决这个问题?

import sys 
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import pyqtgraph as pg
import time
import numpy as np


class Screen(QMainWindow):
    def __init__(self):
        super(Screen, self).__init__()
        self.initUI()

    def initUI(self):
        self.x = np.array([1,2,3,4])
        self.y = np.array([1,4,9,16])
        self.plt = pg.PlotWidget()
        self.plt.plot(self.x, self.y)

        addBtn = QPushButton('Add Datapoint')
        addBtn.clicked.connect(self.addDataToPlot)
        addBtn.show()

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(addBtn)
        mainLayout.addWidget(self.plt)

        self.mainFrame = QWidget()
        self.mainFrame.setLayout(mainLayout)
        self.setCentralWidget(self.mainFrame)

    def addDataToPlot(self):
        data = {
            'x': 5,
            'y': 25
        }
        np.append(self.x, data['x'])
        np.append(self.y, data['y'])
        self.plt.setData(self.x, self.y)


app = QApplication(sys.argv)
window = Screen()
window.show()
sys.exit(app.exec_())

您必须更新绘图中的数据,而不是小部件中的数据,为此我们将其保存为属性。

def initUI(self):
    self.x = np.array([1,2,3,4])
    self.y = np.array([1,4,9,16])
    self.plt = pg.PlotWidget()
    self.plot = self.plt.plot(self.x, self.y)
    [...]

同样在你的情况下没有被更新,函数追加 returns 一个连接输入数据的对象,所以你必须保存它

def addDataToPlot(self):
    [...]
    self.x = np.append(self.x, data['x'])
    self.y =np.append(self.y, data['y'])
    self.plot.setData(self.x, self.y)