【问题标题】:How to clear up the data after I use PlotWidget.plot()?使用 PlotWidget.plot() 后如何清除数据?
【发布时间】:2019-09-29 15:59:36
【问题描述】:

这是我的代码:

import sys
import numpy as np
import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout


class MyGraph(QWidget):
    def __init__(self):
        super(MyGraph, self).__init__()
        self.resize(600, 600)

        pg.setConfigOption('background', 'w')

        x = np.random.normal(size=1000)
        y = np.random.normal(size=1000)

        self.pw = pg.PlotWidget(self)
        self.pw.plot(x, y, pen=None, symbol='o', symbolBrush='r')

        self.plot_btn = QPushButton('Replot', self)
        self.plot_btn.clicked.connect(self.plot_slot)

        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(self.pw)
        self.v_layout.addWidget(self.plot_btn)
        self.setLayout(self.v_layout)

    def plot_slot(self):
        x = np.random.normal(size=1000)
        y = np.random.normal(size=1000)

        # The new data is added to the existed one
        self.pw.plot(x, y, pen=None, symbol='o', symbolBrush='r')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = MyGraph()
    demo.show()
    sys.exit(app.exec_())

每次点击按钮,我都想清理现有数据并重新绘制新数据,但 PlotWidget 似乎没有相关功能让我这样做。

有什么方法可以清理数据吗?

谢谢!

【问题讨论】:

    标签: pyqt pyqt5 pyqtgraph


    【解决方案1】:

    PlotWidget 的 plot 方法生成一个负责绘图的项目,在您的情况下,每次按下按钮时都会创建另一个绘图,因此您观察到 行为。解决方案是重用

    class MyGraph(QWidget):
        def __init__(self):
            super(MyGraph, self).__init__()
            self.resize(600, 600)
    
            pg.setConfigOption("background", "w")
    
            x = np.random.normal(size=1000)
            y = np.random.normal(size=1000)
    
            self.pw = pg.PlotWidget(self)
            self.plot = self.pw.plot(x, y, pen=None, symbol="o", symbolBrush="r")
    
            self.plot_btn = QPushButton("Replot", self, clicked=self.plot_slot)
    
            v_layout = QVBoxLayout(self)
            v_layout.addWidget(self.pw)
            v_layout.addWidget(self.plot_btn)
    
        def plot_slot(self):
            x = np.random.normal(size=1000)
            y = np.random.normal(size=1000)
            self.plot.setData(x, y)
    

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2012-12-16
      • 2014-02-18
      • 2019-09-13
      • 2016-03-11
      相关资源
      最近更新 更多