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

时间:2017-12-25 22:20:05

标签: python pandas matplotlib pyqt pyqt5

到目前为止,我有这段代码: 当它被执行时,你会看到两个主窗口,另一个叫做图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()

1 个答案:

答案 0 :(得分:0)

pandas的plot()函数有一个名为<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.fantappstic_app"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".HomeScreen" android:parentActivityName=".FirstLogin"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SignUpBasicInfo"></activity> </application> </manifest> 的可选属性:

  

ax:matplotlib axes对象,默认无

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

ax