如何在 PyQt4 中使用 matplotlib [英] How to use matplotlib with PyQt4

查看:66
本文介绍了如何在 PyQt4 中使用 matplotlib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 PyQt 中绘制一个带有嵌入式 matplotlib 的图形.我在主窗口使用 Qt Designer,并为信号和插槽连接部分编写 python 代码.

所以我的代码看起来像这样:

导入系统从 PyQt4 导入 QtCore、QtGui、uic从 matplotlib.backends.backend_qt4agg 导入 FigureCanvasQTAgg 作为 FigureCanvas从 matplotlib.backends.backend_qt4agg 导入 NavigationToolbar2QT 作为 NavigationToolbar导入 matplotlib.pyplot 作为 plt将熊猫导入为 pd将 numpy 导入为 npqtCreatorFile = "main.ui" # 我的 Qt 设计器文件Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)类 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)定义图(自我):filePath="/这里是 csv 文件的路径"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(假)ax.plot(df, '*-')self.canvas.draw()如果 __name__ == "__main__":app = QtGui.QApplication(sys.argv)窗口 = MyApp()window.show()sys.exit(app.exec_())

我的主要问题是 Qt Designer 文件和 python 代码之间的连接,我无法直接在 Qt Designer 中设置画布小部件,而且我仍在努力寻找错误在我的代码中的位置.非常感谢您的帮助,谢谢.

解决方案

为了在 Qt Designer 中使用 matplotlib 不能直接完成,为此我们必须推广一个 QWidgetcode> 要使用 FigureCanvas 或更好的继承自它的类,如下所示,首先我们在名为 canvas.py 的文件中创建一个名为 Canvas 的类:

canvas.py

 from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas导入 matplotlib.pyplot 作为 plt类画布(图画布):def __init__(self, parent=None):self.figure = plt.figure()FigureCanvas.__init__(self, self.figure)self.setParent(父母)

通过 Qt Designer 创建设计后,我们拥有了所有想要的元素,但是在我们想要放置参数的地方我们使用 Containers 中的 Widget 元素,我们将其命名为 canvas:

然后我们通过右键单击并选择选项promoted to ...:

获得下图所示的内容,在Promoted Class Name中我们将Canvas作为类名,在Header File中> 我们放置canvas.h(在头文件中放置file.py文件,例如package.subpackage.file.h),然后按 AddPromote 之后:

最后我们得到类似如下的文件结构:

<预><代码>.├──画布.py└── main.ui

然后我们创建文件 main.py,在其中放置您的代码,其中包含一些小的变化:

ma​​in.py

导入 matplotlibmatplotlib.use('Qt4Agg')导入系统从 PyQt4 导入 QtCore、QtGui、uic导入 matplotlib.pyplot 作为 plt将熊猫导入为 pd将 numpy 导入为 npqtCreatorFile = "main.ui" # 我的 Qt 设计器文件Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)类 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)定义图(自我):文件路径=数据.csv"df= pd.read_csv(str(filePath),index_col='date')ax = self.canvas.figure.add_subplot(111)ax.hold(假)ax.plot(df, '*-')self.canvas.draw()如果 __name__ == "__main__":app = QtGui.QApplication(sys.argv)窗口 = MyApp()window.show()sys.exit(app.exec_())

最后我们得到以下内容:

您可以在

I want to plot a figure with embedded matplotlib in PyQt. I am using Qt Designer for the main window, and writing python code for the signal and slots connexion part.

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. 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:

canvas.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:

Then we promote it by right click and choose the option 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:

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

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:

...
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))
        ...

这篇关于如何在 PyQt4 中使用 matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆