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

相关推荐
hboot12 小时前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户83562907805117 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户83562907805118 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠1 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3101 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫1 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780512 天前
使用 Python 操作 Word 内容控件
后端·python
LDR0062 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术2 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript