这是我的代码:
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似乎没有相关功能让我这样做。
有什么方法可以清除数据?
谢谢!
答案 0 :(得分: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)