Simple demonstration of pyqt5 matlibplot combined use (plt can be used directly)

Using matplotlib in Pyqt5

At first I saw QwPlot in qtdesigner, but after checking, I found that it is a c++ library that has not been maintained. Although you can find the corresponding python library made by others, it is not convenient to use. It is recommended to combine matplotlib and pyqt5 to achieve it. Nice drawing effect.

Design the basic framework

To make such an interface in qtdesigner, here I simply put a graohicsView, pay attention to the width and height here, it is best to match the figure when drawing later.
insert image description hereThe content of the .py file generated by using the .ui file is as follows. Of course, you can also skip the UI and directly use this file to test
Test_UI.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Test_UI.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView.setGeometry(QtCore.QRect(150, 120, 500, 300))
        self.graphicsView.setObjectName("graphicsView")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 28))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

The following operations can be divided into two methods, the second method is recommended here, and the first one is used as a reference for understanding

method 1

Create the Figure class

The following minimal example sets up a Matplotlib canvas, FigureCanvasQTAgg, that creates the Figure and adds a set of axes. This canvas object is also a QWidget, so it can be embedded directly into an application like any other Qt widget.

class Figure_Canvas(FigureCanvas):   # 通过继承FigureCanvas类,使得该类既是一个PyQt5的Qwidget,又是一个matplotlib的FigureCanvas,这是连接pyqt5与matplot lib的关键

    def __init__(self, parent=None, width=5, height=3, dpi=100):
        fig = Figure(figsize=(width, height), dpi=100)  # 创建一个Figure,注意:该Figure为matplotlib下的figure,不是matplotlib.pyplot下面的figure

        FigureCanvas.__init__(self, fig) # 初始化父类
        self.setParent(parent)

        self.axes = fig.add_subplot(111) # 调用figure下面的add_subplot方法,类似于matplotlib.pyplot下面的subplot方法

    def test(self):
        x = [1,2,3,4,5,6,7,8,9]
        y = [23,21,32,13,3,132,13,3,1]
        self.axes.plot(x, y)

Put the drawn picture into the interface

Here we inherit our previous interface, execute the drawing operation, put the drawn picture into QGraphicsView, and display it

class Test_window(QtWidgets.QMainWindow,Test_UI.Ui_MainWindow):
    def __init__(self,parent=None):
        super(Test_window,self).__init__(parent)
        self.setupUi(self)
        dr = Figure_Canvas()
        # 实例化一个FigureCanvas
        time1 =time.time()
        dr.test()  # 画图
        graphicscene = QtWidgets.QGraphicsScene()  # 第三步,创建一个QGraphicsScene,因为加载的图形(FigureCanvas)不能直接放到graphicview控件中,必须先放到graphicScene,然后再把graphicscene放到graphicview中
        graphicscene.addWidget(dr)  # 第四步,把图形放到QGraphicsScene中,注意:图形是作为一个QWidget放到QGraphicsScene中的
        self.graphicsView.setScene(graphicscene)  # 第五步,把QGraphicsScene放入QGraphicsView
        self.graphicsView.show()  # 最后,调用show方法呈现图形!
        time2 = time.time()
        print(time2-time1)

In general, such a file
test_qt.py is formed

import matplotlib
matplotlib.use("Qt5Agg")  # 声明使用QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

from PyQt5 import QtWidgets,QtCore
from PyQt5.QtWidgets import QMainWindow,QApplication
import sys

import Test_UI

import time

class Figure_Canvas(FigureCanvas):   # 通过继承FigureCanvas类,使得该类既是一个PyQt5的Qwidget,又是一个matplotlib的FigureCanvas,这是连接pyqt5与matplot lib的关键

    def __init__(self, parent=None, width=5, height=3, dpi=100):
        fig = Figure(figsize=(width, height), dpi=100)  # 创建一个Figure,注意:该Figure为matplotlib下的figure,不是matplotlib.pyplot下面的figure

        FigureCanvas.__init__(self, fig) # 初始化父类
        self.setParent(parent)

        self.axes = fig.add_subplot(111) # 调用figure下面的add_subplot方法,类似于matplotlib.pyplot下面的subplot方法

    def test(self):
        x = [1,2,3,4,5,6,7,8,9]
        y = [23,21,32,13,3,132,13,3,1]
        self.axes.plot(x, y)

class Test_window(QtWidgets.QMainWindow,Test_UI.Ui_MainWindow):
    def __init__(self,parent=None):
        super(Test_window,self).__init__(parent)
        self.setupUi(self)
        dr = Figure_Canvas()
        # 实例化一个FigureCanvas
        time1 =time.time()
        dr.test()  # 画图
        graphicscene = QtWidgets.QGraphicsScene()  # 第三步,创建一个QGraphicsScene,因为加载的图形(FigureCanvas)不能直接放到graphicview控件中,必须先放到graphicScene,然后再把graphicscene放到graphicview中
        graphicscene.addWidget(dr)  # 第四步,把图形放到QGraphicsScene中,注意:图形是作为一个QWidget放到QGraphicsScene中的
        self.graphicsView.setScene(graphicscene)  # 第五步,把QGraphicsScene放入QGraphicsView
        self.graphicsView.show()  # 最后,调用show方法呈现图形!
        time2 = time.time()
        print(time2-time1)




if __name__ == '__main__':
    app = QApplication(sys.argv)
    mytest = Test_window()
    mytest.show()
    app.exec_()

Run it together with the previous Test_UI.py to get the effect
insert image description here

Method 2

Method 1 is a common method on the Internet. I found that it cannot directly use matplotlib.pyplot, so I tested this method and found that it is feasible, so that I can use the pyplot method directly.

    def plot_test(self):
        figure = plt.figure(figsize=(4, 2), dpi=100)
        canvas = FigureCanvas(figure)
        x = np.arange(1, 1000)
        y = x ** 2
        plt.plot(x, y)
        canvas.draw()  # 这是关键
        return canvas

Observing this function, we can know that plt.figure is still used directly, which is different from method 1. Later, we still use FigureCanvas to package this figure to get canvas. The subsequent operations are completely drawn according to plt. Finally, canvas must be added. , draw(), and then return to this canvas to display it directly in pyqt

full code

import matplotlib
matplotlib.use("Qt5Agg")  # 声明使用QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt


import numpy as np

from PyQt5 import QtWidgets,QtCore
from PyQt5.QtWidgets import QMainWindow,QApplication
import sys

import Test_UI

import time


class Test_window(QtWidgets.QMainWindow,Test_UI.Ui_MainWindow):
    def __init__(self,parent=None):
        super(Test_window,self).__init__(parent)
        self.setupUi(self)
        canvas = self.plot_test()
        graphicscene = QtWidgets.QGraphicsScene()  # 第三步,创建一个QGraphicsScene,因为加载的图形(FigureCanvas)不能直接放到graphicview控件中,必须先放到graphicScene,然后再把graphicscene放到graphicview中
        graphicscene.addWidget(canvas)  # 第四步,把图形放到QGraphicsScene中,注意:图形是作为一个QWidget放到QGraphicsScene中的
        self.graphicsView.setScene(graphicscene)  # 第五步,把QGraphicsScene放入QGraphicsView
        self.graphicsView.show()  # 最后,调用show方法呈现图形!

    def plot_test(self):
        figure = plt.figure(figsize=(4, 2), dpi=100)
        canvas = FigureCanvas(figure)
        x = np.arange(1, 1000)
        y = x ** 2
        plt.plot(x, y)
        canvas.draw()  # 这是关键
        return canvas


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mytest = Test_window()
    mytest.show()
    app.exec_()

running result
insert image description here

Guess you like

Origin blog.csdn.net/qin_liang/article/details/127018270