簡體   English   中英

輸入用戶數據時如何通過Matplotlib更新圖(通過PyQt5按鈕)

[英]How to update plot in Matplotlib when user data is inputted (via PyQt5 button)

我整天一直在不懈地編寫此代碼,但似乎無法弄清楚我的邏輯在哪里。 我希望用戶能夠瀏覽一個文件(在這里他們只是按一個名為“瀏覽”的按鈕),該文件可以立即更新顯示的圖(這里從藍線到紅色);但最終在我的實際程序中從空白圖到填充圖,或從填充圖到另一填充圖)。

它的靈感來自https://matplotlib.org/examples/user_interfaces/embedding_in_qt5.html的示例,但是我已經對其進行了相當多的更改,以最有希望的最小和完整的方式表達我的當前問題。 非常感謝您甚至來看看。

import sys
import os
import random
import matplotlib
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QGridLayout, QFileDialog, QPushButton

from numpy import arange
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure


class MyMplCanvas(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        self.compute_initial_figure()

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtWidgets.QSizePolicy.Expanding,
                                   QtWidgets.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass


class MyDynamicMplCanvas(MyMplCanvas):
    """A canvas that updates itself every second with a new plot."""

    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        #timer = QtCore.QTimer(self)
        #timer.timeout.connect(self.update_figure)
        #timer.start(1000)

    def compute_initial_figure(self):
        self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'b')

    def update_figure(self):
        print('update')
        # Build a list of 4 random integers between 0 and 10 (both inclusive)
        l = [random.randint(0, 10) for i in range(4)]
        self.axes.cla()
        if P1.df is True:
            self.axes.plot(P1.df, l, 'r') #should change to red, but doesn't
        else:
            self.axes.plot([0, 1, 2, 3], l, 'b')
        self.draw()

class P1(QtWidgets.QWidget):

    df = False #datafile is originally empty

    def __init__(self, parent=None):
        super(P1, self).__init__(parent)
        layout = QGridLayout(self)

        self.button_browse = QPushButton('Browse', self)
        self.button_browse.clicked.connect(self.browseFile)
        layout.addWidget(self.button_browse, 1, 1, 1, 1)
        self.button_browse.show()

        dc = MyDynamicMplCanvas(self, width=5, height=4, dpi=100)
        layout.addWidget(dc, 2, 1, 1, 1)

    def browseFile(self): #user presses browse to load new datafile
        print(P1.df)
        P1.df = [0, 1, 2, 3] 
        print(P1.df)
        #loading new datafile needs to update plot:
        MyDynamicMplCanvas().update_figure()



class MainWindow(QtWidgets.QMainWindow):    
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        self.stack = QtWidgets.QStackedWidget(self)
        P1f = P1(self)
        self.stack.addWidget(P1f)
        self.setCentralWidget(self.stack)

if __name__ == '__main__':
    qApp = QtWidgets.QApplication(sys.argv)
    aw = MainWindow()
    aw.show()
    sys.exit(qApp.exec_())

您有2個錯誤:

  • 使用MyDynamicMplCanvas().update_figure()您將創建一個新的MyDynamicMplCanvas()對象,該對象與dc = MyDynamicMplCanvas(self, width = 5, height = 4, dpi = 100) ,因此避免了永遠不會使用局部變量所示。

  • 第二個是句子P1.df為True,因為P1.df為False或為列表,所以永遠不會為真。

解決方案是使該類成為成員並if P1.df is True:更改if P1.df is True: if P1.df:

class MyDynamicMplCanvas(MyMplCanvas):
    ...

    def update_figure(self):
        print('update')
        # Build a list of 4 random integers between 0 and 10 (both inclusive)
        l = [random.randint(0, 10) for i in range(4)]
        self.axes.cla()
        if P1.df:
            self.axes.plot(P1.df, l, 'r') #should change to red, but doesn't
        else:
            self.axes.plot([0, 1, 2, 3], l, 'b')
        self.draw()

class P1(QtWidgets.QWidget):
    df = False

    def __init__(self, parent=None):
        ...

        self.dc = MyDynamicMplCanvas(self, width=5, height=4, dpi=100)
        layout.addWidget(self.dc, 2, 1, 1, 1)

    def browseFile(self): #user presses browse to load new datafile
        P1.df = [0, 1, 2, 3]
        #loading new datafile needs to update plot:
        self.dc.update_figure()

...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM