【问题标题】:Unable to Update Pyqtgraph Plot with New Data Point无法使用新数据点更新 Pyqtgraph 图
【发布时间】:2017-09-26 22:23:09
【问题描述】:

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

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

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_())

【问题讨论】:

    标签: python python-2.7 pyqt pyqt4 pyqtgraph


    【解决方案1】:

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

    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)
        [...]
    

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

    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)
    

    【讨论】:

    • 它把所有的情节都画了一遍,有没有什么东西只是在上一张图上加了一个像素?
    猜你喜欢
    • 2020-08-04
    • 2017-04-17
    • 2021-03-24
    • 2014-08-31
    • 2018-04-25
    • 2021-03-31
    • 2017-04-09
    • 2017-07-02
    • 2022-01-06
    相关资源
    最近更新 更多