在PyQt5中插入matplotlab绘图面板

python 复制代码
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy, QPushButton
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import random
 
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = '示例图像'
        self.initUI()
        self.m.plot()  #调用PlotCanvas的函数画图

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, 900, 400) 
        m = PlotCanvas(self, width=7, height=4)
        m.move(0,0)
        self.m = m
        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This s an example button')
        button.move(700,0)
        button.resize(140,100)
        self.show()
 
class PlotCanvas(FigureCanvas):
    def __init__(self, parent=None, width=7, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi) #matplotlab的Figure类
        self.axes = fig.add_subplot(111)
 
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
 
        FigureCanvas.setSizePolicy(self,
                QSizePolicy.Expanding,
                QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
 
    def plot(self):
        data = [random.random() for i in range(25)]
        #ax = self.figure.clear()
        #ax = self.figure.add_subplot(111)
        ax = self.figure.axes[0]  #获取原有的第一个axes
        ax.plot(data, 'r-')  #画图折线图,红色----
        ax.set_title('PyQt Matplotlib Example')
        self.draw()
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

添加一个继承自FigureCanvas的PlotCanvas类。

PlotCanvas类放置在PyQt窗口面板中。

在PlotCanvas类中调用matplotlab的Figure类,再通过获取axes,通过axes画图。

相关推荐
白夜11175 分钟前
C++(标签派发 Tag Dispatching)
开发语言·c++·笔记·算法
WJ.Polar18 分钟前
Scapy基本应用
linux·运维·网络·python
小短腿的代码世界23 分钟前
Qt数据库编程深度解析:从SQL基础到ORM架构设计
数据库·sql·qt
CSCN新手听安35 分钟前
【Qt】Qt窗口(六)QMessageBox消息对话框的使用
开发语言·c++·qt
H_unique37 分钟前
LangChain:调用工具Ⅲ
python·langchain
爱看书的小沐1 小时前
【小沐学WebGIS】基于Cesium.JS与jsbsim联动三维飞行仿真(OpenGL、Cesium.js、Three.js)
c++·qt·three.js·opengl·cesium·jsbsim
醉舞经阁半卷书11 小时前
深入掌握LangChain
python·langchain
CDN3601 小时前
[硬核] 你的DNS正在“裸奔”?用Python手撕DNS劫持与隧道检测逻辑
开发语言·网络·python
froginwe111 小时前
jQuery 添加元素
开发语言
zhangfeng11331 小时前
PHP 语法检查命令 php -l “$file“ > /dev/null 2>&1;
开发语言·php