在pyqt5中使用matplotlib
前言
虽然,qt中也提供了绘图函数,但对于初学者并不是很容易掌握,众所周知,matplot提供了简单,易用,强大的绘图函数,结合mumpy基本可以达到matlb中的绘图体验,并且比matlab更加具有扩展性,也更自由。通过matplotlib提供的官方例程的修改,就可以很容易的绘制你想要的图形,真的很强大。(我也是名初学者)
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代码,这里就不多说了。
写在最后
因为自身能力有限,也不是科班出身,都是自学的,目前还是一名学生,所以有未尽之处还请指正,不喜勿喷。谢谢。