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 :
保存,命名为dym_plot_matplotlib.ui
3、添加按钮控件
添加一个按钮控件pushButton ,在右侧objectName 命名为btn_start
4、添加Group Box盒子控件
用来显示matplotlib组件,在右侧objectName 命名为plot_view :
保存。
5、使用pyuic5.exe把ui转py
使用pyuic5.exe把dym_plot_matplotlib.ui 转dym_plot_matplotlib.py :
其中转化后dym_plot_matplotlib.py 代码为:
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画布,代码如下:
"""
@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):
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)
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)
self.axes.grid(True)
self.axes.set_title('动态曲线 ')
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)
self.axes.set_xlabel('x 坐标 ')
self.axes.set_ylabel('y 坐标 ')
self.axes.add_line(self.line)
7、创建dym_plot_mpl_main.py
在dym_plot_matplotlib.py 同级目录下创建dym_plot_mpl_main.py ,用来启动界面,代码如下:
"""
@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 后,效果图:
源码示例下载
传送门
后记
【后记】为了让大家能够轻松学编程,我创建了一个公众号【轻松学编程】,里面有让你快速学会编程的文章,当然也有一些干货提高你的编程水平,也有一些编程项目适合做一些课程设计等课题。
也可加我微信【1257309054】,拉你进群,大家一起交流学习。 如果文章对您有帮助,请我喝杯咖啡吧!
公众号
关注我,我们一起成长~~
|