PyQt5 Qt Designer 使用Matpoltlib画图显示动态曲线

源码示例下载

​传送门​

效果图:
pyqt5 Qt Designer + matpoltlib画图显示动态曲线_开发语言

导入pyqt5库:

pip install PyQt5==5.15.4 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pyqt5-plugins==5.15.4.2.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install PyQt5-Qt5==5.15.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install PyQt5-sip==12.9.1 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install PyQt5-stubs==5.15.2.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pyqt5-tools==5.15.4.3.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install python-dotenv==0.20.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install qt5-applications==5.15.2.2.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install qt5-tools==5.15.2.1.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install numpy==1.21.6 -i https://pypi.tuna.tsinghua.edu.cn/simple

二、使用Matplotlib

1、导入库

pip install  matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple

2、打开Qt Designer

创建一个​​Main Windows​​​:
pyqt5 Qt Designer + matpoltlib画图显示动态曲线_微信_02

保存,命名为​​dym_plot_matplotlib.ui​

3、添加按钮控件

添加一个按钮控件​​pushButton​​​,在右侧​​objectName​​​命名为​​btn_start​​​pyqt5 Qt Designer + matpoltlib画图显示动态曲线_qt_03

4、添加Group Box盒子控件

用来显示matplotlib组件,在右侧​​objectName​​​命名为​​plot_view​​​:
pyqt5 Qt Designer + matpoltlib画图显示动态曲线_开发语言_04

保存。

5、使用pyuic5.exe把ui转py

使用pyuic5.exe把​​dym_plot_matplotlib.ui​​​转​​dym_plot_matplotlib.py​​​:
pyqt5 Qt Designer + matpoltlib画图显示动态曲线_开发语言_05

其中转化后​​dym_plot_matplotlib.py​​代码为:

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

# Form implementation generated from reading ui file 'dym_plot_matplotlib.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# 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, 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.btn_start = QtWidgets.QPushButton(self.centralwidget)
self.btn_start.setGeometry(QtCore.QRect(50, 40, 93, 28))
self.btn_start.setObjectName("btn_start")
self.plot_view = QtWidgets.QGroupBox(self.centralwidget)
self.plot_view.setGeometry(QtCore.QRect(39, 100, 731, 311))
self.plot_view.setObjectName("plot_view")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
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"))
self.btn_start.setText(_translate("MainWindow", "开始"))
self.plot_view.setTitle(_translate("MainWindow", "GroupBox"))

6、创建一个mpl_plot.py

在​​dym_plot_matplotlib.py​​​同级目录下创建​​mpl_plot.py​​,用来渲染matplotlib画布,代码如下:

# !/usr/bin/python
# -*- coding: utf-8 -*-

"""
@contact: 微信 1257309054
@file: mpl_plot.py
@time: 2022/5/23 15:05
@author: LDC
"""

import matplotlib
import numpy as np
matplotlib.use("Qt5Agg")
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from PyQt5 import QtWidgets
from matplotlib.lines import Line2D
from matplotlib.figure import Figure
import matplotlib.pyplot as plt


class Mplplot(FigureCanvas):
def __init__(self, parent=None, width=5, height=3, dpi=100):
# normalized for 中文显示和负号
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

self.fig = Figure(figsize=(width, height), dpi=dpi)
super(Mplplot, self).__init__(self.fig)
self.setParent(parent)
self.axes = self.fig.add_subplot(111) # 111 表示 1 行 1 列,第一张曲线图


FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)

def add_line(self, x_data, y_data):
self.line = Line2D(x_data, y_data) # 绘制 2D 折线图
# ------------------ 调整折线图基本样式 ---------------------#
# self.line.set_ls('--') # 设置连线
# self.line.set_marker('*') # 设置每个点
# self.line.set_color('red') # 设置线条颜色
self.axes.grid(True) # 添加网格
self.axes.set_title('动态曲线 ') # 设置标题
# 设置 xy 轴最大最小值 , 找到 x_data, y_data 最大最小值
self.axes.set_xlim(np.min(x_data), np.max(x_data))
self.axes.set_ylim(np.min(y_data), np.max(y_data) + 5) # y 轴稍微多一点,会好看一点
self.axes.set_xlabel('x 坐标 ') # 设置坐标名称
self.axes.set_ylabel('y 坐标 ')
# 在曲线下方填充颜色
# self.ax.fill_between(x_data, y_data, color='g', alpha=0.1)
# self.ax.legend([self.line], ['sinx']) # 添加图例
# ------------------------------------------------------#
self.axes.add_line(self.line)

7、创建dym_plot_mpl_main.py

在​​dym_plot_matplotlib.py​​​同级目录下创建​​dym_plot_mpl_main.py​​,用来启动界面,代码如下:

# !/usr/bin/python
# -*- coding: utf-8 -*-

"""
@contact: 微信 1257309054
@file: dym_plot_mpl_main.py
@time: 2022/5/25 17:14
@author: LDC
"""

import json

import numpy as np
import logging
import os

import time
import sys

from PyQt5.Qt import *
from dym_plot_matplotlib import Ui_MainWindow
from mpl_plot import Mplplot
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar
from scipy.interpolate import make_interp_spline


class Window(QMainWindow, Ui_MainWindow):
'''
pyqt5界面流程
'''

def __init__(self, app):
super(QMainWindow, self).__init__()
self.app = app
self.setup_ui() # 渲染画布
self.update_data_thread = UpdateDataThread() # 创建更新波形数据线程
self.connect_signals() # 绑定触发事件

def setup_ui(self):
self.setupUi(self)
# 加载相位振动波形
self.phase_fig = Mplplot(width=5, height=3, dpi=72)
self.fig_ntb = NavigationToolbar(self.phase_fig, self)
self.gridlayout = QGridLayout(self.plot_view)
self.gridlayout.addWidget(self.phase_fig)
self.gridlayout.addWidget(self.fig_ntb)
# 准备数据,绘制曲线
self.x_data = np.arange(-10, 10, 0.1)
y_data = np.sin(self.x_data)
self.phase_fig.add_line(self.x_data, y_data)

def connect_signals(self):
# 绑定触发事件
self.btn_start.clicked.connect(self.btn_start_clicked)
self.update_data_thread._signal_update.connect(self.update_data_thread_slot) # 绑定回调事件

def btn_start_clicked(self):
# 开启按钮
self.update_data_thread.start()
self.update_data_thread.x_data = self.x_data

def update_data_thread_slot(self, data):
# 线程回调函数
data = json.loads(data)
print(data['sin_data'])
self.phase_fig.line.set_ydata(data['sin_data']) # 更新数据
self.phase_fig.draw() # 重新画图


# 使用线程不断更新波形数据
class UpdateDataThread(QThread):
_signal_update = pyqtSignal(str) # 信号

def __init__(self, parent=None):
super(UpdateDataThread, self).__init__(parent)
self.qmut = QMutex()
self.is_exit = False
self.ts = time.time()
self.x_data = None

def run(self):
while True:
self.qmut.lock()
if self.is_exit:
break
self.qmut.unlock()
dt = time.time() - self.ts
z_data = np.sin(self.x_data + dt) # 准备动态数据

self._signal_update.emit(json.dumps({'sin_data': z_data.tolist()})) # 发送信号给槽函数
time.sleep(1)
self.qmut.unlock()


def main():
app = QApplication(sys.argv)
mywindow = Window(app)
mywindow.show()
sys.exit(app.exec_())


if __name__ == '__main__':
main()

运行​​dym_plot_mpl_main.py​​​后,效果图:
pyqt5 Qt Designer + matpoltlib画图显示动态曲线_微信_06

源码示例下载

​传送门​

后记

公众号

pyqt5 Qt Designer + matpoltlib画图显示动态曲线_开发语言_07

关注我,我们一起成长~~