如何在窗口小部件中使用pandas.plot()的matplotlib图?

问题描述 投票:0回答:1

到目前为止,我有这样的代码:当它被执行时,你会看到两个windows main和另一个叫做图1,当csv数据被加入时,按下情节按钮,图形显示在另一个窗口中(图2)我能解决这个问题吗?很多,非常感谢你的时间!

import sys
import pandas as pd
import matplotlib
matplotlib.use('QT5Agg')
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')


class Window(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(600,300, 1000, 600)
        self.center()
        grid = QtWidgets.QGridLayout()
        widget = QtWidgets.QWidget(self)
        self.setCentralWidget(widget)
        widget.setLayout(grid)
         #Import CSV Button
        btn1 = QtWidgets.QPushButton('Import CSV', self)
        btn1.resize(btn1.sizeHint())
        btn1.clicked.connect(self.getCSV)
        grid.addWidget(btn1, 1, 0)

        self.figure = plt.figure(figsize=(15,5))    
        self.canvas = FigureCanvas(self.figure)     
        grid.addWidget(self.canvas, 2,0,1,2)


        btn2 = QtWidgets.QPushButton('Plot', self)
        btn2.resize(btn2.sizeHint())    
        btn2.clicked.connect(self.plot)
        grid.addWidget(btn2, 1, 1)
        self.show()

    def plot(self):
        self.df.plot(x='col1',y='col2')
        self.canvas.draw()

    def getCSV(self):
         filePath, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', '/home')
         if filePath != "":
            print ("Dirección",filePath)
            self.df = pd.read_csv(str(filePath))

    def center(self):
        qr = self.frameGeometry()
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

def main():
    app = QtWidgets.QApplication(sys.argv)
    w = Window()
    sys.exit(app.exec_())


if __name__ == '__main__':
   main()
python pandas matplotlib pyqt pyqt5
1个回答
0
投票

pandas的plot()函数有一个名为ax的可选属性:

ax:matplotlib轴对象,默认无

如果我们想要在FigureCanvas()中绘制它,你必须首先创建一些轴,并将其作为ax中的属性传递:

def plot(self):
    self.figure.clear()
    ax =  self.figure.add_subplot(111) 
    self.df.plot(x='col1',y='col2', ax=ax)
    self.canvas.draw()
© www.soinside.com 2019 - 2024. All rights reserved.