matplotlib嵌入到pyqt中

在pyqt5中使用matplotlib

前言

虽然,qt中也提供了绘图函数,但对于初学者并非很容易掌握,众所周知,matplot提供了简单,易用,强大的绘图函数,结合mumpy基本能够达到matlb中的绘图体验,而且比matlab更加具备扩展性,也更自由。经过matplotlib提供的官方例程的修改,就能够很容易的绘制你想要的图形,真的很强大。(我也是名初学者)python

matplotlib,pyqt5官方例程

# 取自matplotlib 官方文档案例

from __future__ import unicode_literals
import sys
import os
import random
import matplotlib
# Make sure that we are using QT5
matplotlib.use('Qt5Agg')

from PyQt5 import QtCore, QtWidgets
from numpy import arange, sin, pi, linspace
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

progname = os.path.basename(sys.argv[0])
progversion = "0.1"


class MyMplCanvas(FigureCanvas):
    # 这既是一个wiget类也是一个FigureCanva

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

        self.compute_initial_figure()

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

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

    def compute_initial_figure(self):
        pass


class MyStaticMplCanvas(MyMplCanvas):
    """Simple canvas with a sine plot."""

    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        

    def compute_initial_figure(self):
        print("hello world")
        x = linspace(0, 2 * pi, 500000)
        y = sin(x)
        self.axes.cla()
        self.axes.plot(x, y)
        self.draw()


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], 'r')

    def update_figure(self):
        # 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()
        self.axes.plot([0, 1, 2, 3], l, 'r')
        self.draw()


class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("application main window")

        self.file_menu = QtWidgets.QMenu('&File', self)
        self.file_menu.addAction('&Quit', self.fileQuit,
                                 QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)

        self.help_menu = QtWidgets.QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)

        self.help_menu.addAction('&About', self.about)

        self.main_widget = QtWidgets.QWidget(self)

        l = QtWidgets.QVBoxLayout(self.main_widget)
        sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        dc = MyDynamicMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        l.addWidget(sc)
        l.addWidget(dc)

        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

        self.statusBar().showMessage("All hail matplotlib!", 2000)

    def fileQuit(self):
        self.close()

    def closeEvent(self, ce):
        self.fileQuit()

    def about(self):
        QtWidgets.QMessageBox.about(self, "About",
                                    """embedding_in_qt5.py example
Copyright 2005 Florent Rougon, 2006 Darren Dale, 2015 Jens H Nielsen

This program is a simple example of a Qt5 application embedding matplotlib
canvases.

It may be used and modified with no restriction; raw copies as well as
modified versions may be distributed without limitation.

This is modified from the embedding in qt4 example to show the difference
between qt4 and qt5""")

代码解析

经过matplotlib.use('Qt5Agg'),这行代码声明matplotlib将要嵌入到pyqt5中,一样经过这句,也能够声明将matplotlib嵌入到其余的,gui界面中去,而后经过继承FigureCanvas类来得到一个即便widget的类也是FigureCanva类的类,而后经过self.fig成员,生成一个绘图类,并由其建立一个绘图布局,返回一个self.axes来管理绘图布局中的内容。坐标轴,标题,标签,图形样式(饼图,柱状图,折线图等)等等的设置都经过self.axes的成员函数来设置完成。刚开始的使用仍是比较云里雾里的,如今就差很少了。我对官方例程作了些修改,具体的代码,能够到个人GitHub仓储上查看Qt-learn-pyqt5-matplotlib里面也有一些其余的例子,应该还会不按期的更新,有兴趣也能够看看。下面只须要对这几个类进行实例话,开启qt的事件循环就能够看到界面了,具体的能够看个人github代码,这里就很少说了。git

写在最后

由于自身能力有限,也不是科班出身,都是自学的,目前仍是一名学生,因此有未尽之处还请指正,不喜勿喷。谢谢。github

相关文章
相关标签/搜索