在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画图。

相关推荐
zone773915 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant15 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来16 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_16 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend17 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽17 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
blasit1 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang2 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮2 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python