Matplotlib画图教程:在QT界面中嵌入三维图片
生活随笔
收集整理的這篇文章主要介紹了
Matplotlib画图教程:在QT界面中嵌入三维图片
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Matplotlib畫圖教程:在QT界面中嵌入三維圖片
需求:
做項目報告的時候,有這么一個想法,就是能通過UI隨時調(diào)用matplotlib進行二維圖和三維圖的繪制。因此就誕生了做這么一個小模塊的想法。
這里先上一下最終結(jié)果:
思路:
pyqt5內(nèi)嵌matploblib畫布。
matplotlib畫布中有一個FigureCanvasQTAgg的模塊可以用于UI繪制
模塊設(shè)計思路:
1. ui文件
ui文件是通過qtdesigner直接生成的ui源碼,與圖表繪制相獨立。
2. 圖表繪制文件
該文件用于設(shè)計一個matplotlib圖表繪制類,存放我們需要做報告的任何圖圖表,以及我們的一些數(shù)據(jù)導(dǎo)入。
3. 運行文件
運行文件繼承上面兩個文件,運行實例。
UI模塊
這個模塊沒什么好說的,基于QTdesigner進行圖形繪制,圖形界面已經(jīng)每個組件定義如下。(這個模塊在教程中只是用于演示)
1.1 UI圖形類
| 實例化方式 | 不需要入?yún)?/strong> | |
| 方法 | ||
| self.setupUi | 構(gòu)建一個UI窗口 |
1.2 測試UI界面及其屬性
繪制的界面樣式
界面控件屬性
1.3 代碼
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'ui_ut.ui' # # Created by: PyQt5 UI code generator 5.15.6 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing.from PyQt5 import QtCore, QtGui, QtWidgetsclass Ui_matplot_demo(object):def setupUi(self, matplot_demo):matplot_demo.setObjectName("matplot_demo")matplot_demo.resize(1133, 721)self.gridLayout = QtWidgets.QGridLayout(matplot_demo)self.gridLayout.setObjectName("gridLayout")self.bt_close = QtWidgets.QPushButton(matplot_demo)self.bt_close.setObjectName("bt_close")self.gridLayout.addWidget(self.bt_close, 1, 1, 1, 1)self.bt_open = QtWidgets.QPushButton(matplot_demo)self.bt_open.setObjectName("bt_open")self.gridLayout.addWidget(self.bt_open, 1, 0, 1, 1)self.plt3d_module = QtWidgets.QWidget(matplot_demo)self.plt3d_module.setMinimumSize(QtCore.QSize(1111, 611))self.plt3d_module.setObjectName("plt3d_module")self.gridLayout.addWidget(self.plt3d_module, 0, 0, 1, 2)self.retranslateUi(matplot_demo)QtCore.QMetaObject.connectSlotsByName(matplot_demo)def retranslateUi(self, matplot_demo):_translate = QtCore.QCoreApplication.translatematplot_demo.setWindowTitle(_translate("matplot_demo", "Form"))self.bt_close.setText(_translate("matplot_demo", "按一下就可以關(guān)閉圖片"))self.bt_open.setText(_translate("matplot_demo", "按一下就可以畫圖"))圖表繪制模塊
這個模塊是核心的圖表繪制模塊,主要結(jié)構(gòu)如下
1.1 依賴包
| numpy | 數(shù)學(xué)運算包 | pip install numpy |
| matplotlilb | 數(shù)學(xué)繪圖包 | pip install matplotlib |
1.2 類
| 實例化方式 | 入?yún)?/strong> | 含義 |
| width=5 | 控制畫布寬度 | |
| height=4 | 控制畫布高度 | |
| dpi=100 | 控制畫布分辨率 | |
| 屬性 | 含義 | 初值 |
| self.fig | 實例化一個matplotlib的Figure類 | |
| self.axes | 坐標系,可以是二維,也可以是三維 | |
| 方法 | ||
| plot_sin | 畫一個正弦函數(shù) | |
| plot_cos | 畫一個余弦函數(shù) | |
| plot_3d | 畫一個3D的圖(基于leetcode218 天際線) |
1.3 代碼如下
import numpy as np import matplotlib from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure matplotlib.use("Qt5Agg") # 聲明使用QT5# 創(chuàng)建一個matplotlib圖形繪制類 class MyFigure(FigureCanvas):def __init__(self, width=5, height=4, dpi=100):# 第一步:創(chuàng)建一個創(chuàng)建Figureself.fig = Figure(figsize=(width, height), dpi=dpi)# 第二步:在父類中激活Figure窗口super(MyFigure, self).__init__(self.fig) # 此句必不可少,否則不能顯示圖形# 第三步:創(chuàng)建一個子圖,用于繪制圖形用,111表示子圖編號,如matlab的subplot(1,1,1)self.axes = None# 第四步:就是畫圖,【可以在此類中畫,也可以在其它類中畫】def plot_sin(self):self.axes = self.fig.add_subplot(111)t = np.arange(0.0, 3.0, 0.01)s = np.sin(2 * np.pi * t)self.axes.plot(t, s)def plot_cos(self):self.axes = self.fig.add_subplot(111)t = np.arange(0.0, 3.0, 0.01)s = np.sin(2 * np.pi * t)self.axes.plot(t, s)def plot_3d(self):self.axes = self.fig.add_subplot(111, projection='3d')x_edges = np.array([[10, 20], [10, 20], [10, 20], [10, 20],[20, 30], [20, 30], [20, 30], [20, 30],[30, 40], [30, 40], [30, 40], [30, 40],[40, 50], [40, 50], [40, 50], [40, 50]])# 設(shè)置y軸取值y_edges = np.array([[10, 20], [20, 30], [30, 40], [40, 50],[10, 20], [20, 30], [30, 40], [40, 50],[10, 20], [20, 30], [30, 40], [40, 50],[10, 20], [20, 30], [30, 40], [40, 50],[10, 20], [20, 30], [30, 40], [40, 50]])# 設(shè)置X,Y對應(yīng)點的值。即原始數(shù)據(jù)。hist = np.array([[3.0], [0.0], [8.0], [4.0],[2.0], [4.0], [5.0], [7.0],[9.0], [2.0], [6.0], [3.0],[0.0], [3.0], [1.0], [0.0]])color_list = ['skyblue', 'lightgreen', 'bisque', 'gold','lightgreen', 'bisque', 'gold', 'lightpink','bisque', 'gold', 'lightpink', 'plum','gold', 'lightpink', 'plum', 'lightgray']for i in range(len(x_edges)):# 設(shè)置作圖點的坐標xpos, ypos = np.meshgrid(x_edges[i][:-1] - 2.5, y_edges[i][:-1] - 2.5)xpos = xpos.flatten('F')ypos = ypos.flatten('F')zpos = np.zeros_like(xpos)# 設(shè)置柱形圖大小dx = 5 * np.ones_like(zpos)dy = dx.copy()dz = hist[i].flatten()# 設(shè)置坐標軸標簽self.axes.set_xlabel('front')self.axes.set_ylabel('side')self.axes.set_zlabel('height')self.axes.bar3d(xpos, ypos, zpos, dx, dy, dz, color=color_list[i], zsort='average')運行模塊
1.1 依賴包
| sys | 系統(tǒng)包 | - |
| PyQt5 | UI包 | pip install pyqt5 |
| 項目包 | ||
| ui_ut | UI模塊 | |
| leetcode218_figure | 圖表繪制模塊 |
1.2 類
| 繼承父類 | ||
| QWidget | ||
| Ui_matplot_demo | ||
| 實例化方式 | 入?yún)?/strong> | 含義 |
| 不需要入?yún)嵗?/td> | ||
| 屬性 | 含義 | 初值 |
| self.F | 實例化一個MyFigure的圖表繪制類 | |
| 方法 | ||
| open_pic | 在UI中畫圖,綁定bt_open控件 | |
| close_pic | 關(guān)閉圖片,綁定bt_close控件 |
1.3 最后再封裝一個main函數(shù)調(diào)用,代碼如下:
import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from ui_ut import Ui_matplot_demo from leetcode218_figure import MyFigureclass myWindow(QWidget, Ui_matplot_demo):def __init__(self):super(myWindow, self).__init__()self.setupUi(self)self.setWindowTitle("顯示matplotlib繪制圖形")self.setMinimumSize(0, 0)# 第五步:定義MyFigure類的一個實例self.F = MyFigure(width=10, height=6, dpi=100)self.F.plot_cos()# 第六步:在GUI的groupBox中創(chuàng)建一個布局,用于添加MyFigure類的實例(即圖形)后其他部件。# 在容器中添加一個groupbox對象,在groupbox對象中創(chuàng)建布局self.groupBox = QGroupBox(self.plt3d_module)self.groupBox.setMinimumSize(QSize(1100, 610))self.groupBox.setTitle("畫圖demo")def connect_bind():self.bt_open.clicked.connect(self.open_pic)self.bt_close.clicked.connect(self.close_pic)connect_bind()self.glo_plt_figure = QGridLayout(self.groupBox)def open_pic(self):self.F = MyFigure(width=10, height=6, dpi=100)self.F.plot_3d()self.glo_plt_figure.addWidget(self.F, 0, 0)print("here")self.show()self.glo_plt_figure.addWidget(self.F, 0, 0)def close_pic(self):self.glo_plt_figure.removeWidget(self.F)self.show()def main():app = QApplication(sys.argv)win = myWindow()win.show()sys.exit(app.exec_())if __name__ == "__main__":main()總結(jié)
以上是生活随笔為你收集整理的Matplotlib画图教程:在QT界面中嵌入三维图片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle 11g ora 15018
- 下一篇: C/C++队列与循环队列