简体   繁体   English

如何在 PyQt4 中使用 matplotlib

[英]How to use matplotlib with PyQt4

I want to plot a figure with embedded matplotlib in PyQt.我想在 PyQt 中绘制一个带有嵌入式 matplotlib 的图形。 I am using Qt Designer for the main window, and writing python code for the signal and slots connexion part.我在主窗口使用 Qt Designer,并为信号和插槽连接部分编写 python 代码。

So my code looks like this :所以我的代码是这样的:

import sys
from PyQt4 import QtCore, QtGui, uic
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas 
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np


qtCreatorFile = "main.ui" # my Qt Designer file 

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        self.figure = plt.figure()

        self.canvas = FigureCanvas(self.figure)

        self.csvbutton.clicked.connect(self.plot)

    def plot(self):

        filePath="/path to csv file here"
        df= pd.read_csv(str(filePath),index_col='date')
        df.index = pd.to_datetime(df.index, unit='s')
        ax = self.figure.add_subplot(111)
        ax.hold(False)
        ax.plot(df, '*-')
        self.canvas.draw()



if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

My main problem is the connexion between the Qt Designer file and the python code, I couldn't set a canvas widget directly in Qt Designer and I'm still struggling to find where the error lays in my code.我的主要问题是 Qt Designer 文件和 python 代码之间的连接,我无法直接在 Qt Designer 中设置画布小部件,而且我仍在努力寻找错误在我的代码中的位置。 Your help is very appreciated, thank you.非常感谢您的帮助,谢谢。

In order to use matplotlib in Qt Designer can not be done directly, for this we must promote a QWidget to use FigureCanvas or better a class that inherits from it as I show below, first we create a class called Canvas in file called canvas.py:为了在 Qt Designer 中使用matplotlib不能直接完成,为此我们必须提升一个QWidget以使用FigureCanvas或更好的继承自它的类,如下所示,首先我们在名为 canvas.py 的文件中创建一个名为 Canvas 的类:

canvas.py画布.py

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas 
import matplotlib.pyplot as plt

class Canvas(FigureCanvas):
    def __init__(self, parent=None):
        self.figure = plt.figure()
        FigureCanvas.__init__(self, self.figure)
        self.setParent(parent)

After creating the design through Qt Designer, we have all the elements we want, but where we want to place the argument we use the Widget element that is in Containers , and we name it canvas :通过 Qt Designer 创建设计后,我们拥有了我们想要的所有元素,但是在我们想要放置参数的地方我们使用了ContainersWidget元素,我们将其命名为canvas

在此处输入图片说明

Then we promote it by right click and choose the option promoted to ... :然后我们通过右键单击来提升它并选择promoted to ...的选项:

在此处输入图片说明

Obtaining what is shown in the following image, in Promoted Class Name we place Canvas as the name of the class, and in Header File we place canvas.h (in Header File the file.py file is placed, for example package.subpackage.file.h ), then press Add and after Promote :获得下图所示的内容,在Promoted Class Name我们放置Canvas作为Promoted Class Name ,在Header File放置canvas.h (在Header File中放置file.py文件,例如package.subpackage.file.h ),然后按AddPromote

在此处输入图片说明

At the end we get a file structure similar to the following:最后我们得到一个类似于以下的文件结构:

.
├── canvas.py
└── main.ui

Then we create the file main.py where we place your code with small variations:然后我们创建文件 main.py,我们将您的代码放置在其中,并带有一些小的变化:

main.py主文件

import matplotlib
matplotlib.use('Qt4Agg')

import sys
from PyQt4 import QtCore, QtGui, uic
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np


qtCreatorFile = "main.ui" # my Qt Designer file 

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.csvbutton.clicked.connect(self.plot)

    def plot(self):

        filePath="data.csv"
        df= pd.read_csv(str(filePath),index_col='date')
        ax = self.canvas.figure.add_subplot(111)
        ax.hold(False)
        ax.plot(df, '*-')
        self.canvas.draw()



if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

In the end we get the following:最终我们得到以下结果:

在此处输入图片说明

You can find the complete project here你可以在这里找到完整的项目


If you want to add the NavigationToolbar you can use the following code:如果要添加 NavigationToolbar,可以使用以下代码:

...
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar 

...

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.addToolBar(NavigationToolbar(self.canvas, self))
        ...

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM