如何刷新matplotlib小部件?

时间:2020-03-09 13:27:09

标签: python matplotlib pyqt5

我正在做一个pyqt5应用程序,有些图表应该每五秒钟更新一次。为简单起见,我创建了一个带有图形的小窗口和一个用于更新图形的小按钮。首先,为了更新图形,我使用了setParent(None)方法,然后创建了一个新的图形对象。我认为这不是一个好主意(因为一段时间后生成了太多图表,导致应用崩溃)。因此,我决定以某种方式重用第一个图形对象,然后调用一个刷新它的函数。我编写了以下代码,该代码在单击按钮时(但仅在拖动窗口的边框之后)才刷新图形:

from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QApplication, QWidget,QVBoxLayout,QPushButton,QTabWidget
import sys
import random
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

x1 =[]
y1 = []
colors = ["purple", "lime", "magenta", "red", "blue", "orange"]

class Canvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=5, dpi=50):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = self.fig.add_subplot(111)
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)
        self.plot()

    def clear(self):
        self.fig.clf()

    def plot(self):
        print("H")
        x1 = []
        y1 = []
        for i in range(100):
            x1.append(i*5)
            y1.append(random.randrange(0, 2000))
        ax = self.figure.add_subplot(111)
        ax.plot(x1, y1, color= colors[random.randint(0, len(colors)-1)])


class MainWindow(QDialog):
    def __init__(self):
        super().__init__()
        self.setGeometry(7, 55,600, 600)
        graphsArea = QVBoxLayout(self)
        bbb = QPushButton("UPDATE GRAPHS")
        bbb.clicked.connect(lambda : self.testf())

        graphsArea.addWidget(bbb)
        self.graph1 = Canvas()

        self.tabs = QTabWidget()
        self.graph = QWidget()
        self.graph.layout = QVBoxLayout( self.graph)
        self.graph.layout.addWidget(self.graph1)
        self.tabs.addTab(self.graph, "Graph1")
        graphsArea.addWidget(self.tabs)
        self.show()

    def testf(self):
        print("hhh")
        self.graph1.clear()
        self.graph1.plot()

if __name__ == '__main__':
    App = QApplication(sys.argv)
    App.setStyle('Fusion')
    window = MainWindow()
    sys.exit(App.exec())

那么,如何在单击按钮后立即更新图形?

0 个答案:

没有答案