pyqt5与matplotlib结合画图

go 复制代码
import numpy as np
import sys
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
from pylab import *

mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
# 使用 matplotlib中的FigureCanvas (在使用 Qt5 Backends中 FigureCanvas继承自QtWidgets.QWidget)
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
from PyQt5.QtCore import QTimer
import sys

from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt


class App(QWidget):
    def __init__(self, parent=None):
        # 父类初始化方法
        super(App, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.setWindowTitle('动态演示')
        self.setWindowIcon(QIcon('电力图标.jpg'))
        self.setWindowIcon(QIcon('2345_image_file_copy_1.jpg'))
        self.setFixedSize(1200, 700)
        self.setMinimumSize(1200, 700)
        self.setMaximumSize(1200, 700)
        # 几个QWidgets
  
        self.startBtn = QPushButton('开始')
        self.endBtn = QPushButton('结束')
        self.startBtn.clicked.connect(self.startTimer)
        self.endBtn.clicked.connect(self.endTimer)
        # 时间模块
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.showTime)
        #图像模块
        self.figure = plt.figure()#***********图像模块********************
        self.canvas = FigureCanvas(self.figure)#***********图像模块********************
        #垂直布局

        layout=QVBoxLayout()
        layout.addWidget(self.startBtn)
        layout.addWidget(self.endBtn)
        layout.addWidget( self.canvas )#***********图像模块********************
        self.setLayout(layout)



        # 数组初始化
        self.x=[]

    def showTime(self):
        shuju=np.random.random_sample()*10#返回一个[0,1)之间的浮点型随机数*10
        self.x.append(shuju)#数组更新
        ax = self.figure.add_axes([0.1, 0.1, 0.8, 0.8])
        ax.clear()
        ax.plot(self.x)
        self.canvas.draw()
    # 启动函数
    def startTimer(self):
        # 设置计时间隔并启动
        self.timer.start(1000)#每隔一秒执行一次绘图函数 showTime
        self.startBtn.setEnabled(False)#开始按钮变为禁用
        self.endBtn.setEnabled(True)#结束按钮变为可用
    def endTimer(self):
        self.timer.stop()#计时停止
        self.startBtn.setEnabled(True)#开始按钮变为可用
        self.endBtn.setEnabled(False)#结束按钮变为可用
        self.x=[]#清空数组
        


# 运行程序
if __name__ == '__main__':
    # QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    main_window = App()
    main_window.show()
    app.exec()

plt.ion()模式动态画图

pip install --upgrade PyQt5

pip install PyQt5-sip==12.11.0 -i https://pypi.tuna.tsinghua.edu.cn/simple

go 复制代码
import matplotlib.pyplot as plt
import numpy as np
# 启动交互模式
plt.ion()
# 创建一个空的图形
fig = plt.figure()
# 循环创建数据并绘制图像
for i in range(10):
    # 创建数据
    x = np.linspace(0, 2*np.pi, 100)
    y = np.sin(x + i*0.1)
    # 清除当前图形
    plt.clf()
    # 绘制新的图像
    plt.plot(x, y)
    # 显示图像
    plt.draw()
    # 暂停一段时间,让图像更新
    plt.pause(0.1)
# 关闭交互模式
plt.ioff()
# 显示最终的图像
plt.show()
go 复制代码
#!/usr/bin/python
# -*- coding:utf-8 -*-
 
from __future__ import unicode_literals
import sys
import os
import random
import matplotlib
# Make sure that we are using QT5
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtWidgets
 
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
 
progname = os.path.basename(sys.argv[0])
progversion = "0.1"
 
 
class MyMplCanvas(FigureCanvas):
    """ 继承FigureCanvasQTAgg的基类,是一个canvas控件。"""
 
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)    # 1行1列索引1
 
        self.compute_initial_figure()   # 画图函数
 
        FigureCanvas.__init__(self, fig)    # 调用父类的初始化函数
        self.setParent(parent)  # 设置上层控件
 
        FigureCanvas.setSizePolicy(self,
                                   QtWidgets.QSizePolicy.Expanding,
                                   QtWidgets.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)   # 刷新布局
 
    def compute_initial_figure(self):
        """ 画图操作函数 """
        pass
 
 
class MyStaticMplCanvas(MyMplCanvas):
    """Simple canvas with a sine plot."""
 
    def compute_initial_figure(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2*pi*t)
        self.axes.plot(t, s)
 
 
class MyDynamicMplCanvas(MyMplCanvas):
    """A canvas that updates itself every second with a new plot."""
 
    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.update_figure)
        timer.start(1000)
 
    def compute_initial_figure(self):
        self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')
 
    def update_figure(self):
        # Build a list of 4 random integers between 0 and 10 (both inclusive)
        l = [random.randint(0, 10) for i in range(4)]
        self.axes.cla()     # 清空子图
        self.axes.plot([0, 1, 2, 3], l, 'r')    # 设置折线点
        self.draw()     # 重新画图
 
 
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("application main window")
 
        self.file_menu = QtWidgets.QMenu('&File', self)
        self.file_menu.addAction('&Quit', self.fileQuit, QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)
 
        self.help_menu = QtWidgets.QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)
 
        self.help_menu.addAction('&About', self.about)
 
        self.main_widget = QtWidgets.QWidget(self)
 
        l = QtWidgets.QVBoxLayout(self.main_widget)
        sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        dc = MyDynamicMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        l.addWidget(sc)
        l.addWidget(dc)
 
        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)
 
        self.statusBar().showMessage("All hail matplotlib!", 2000)
 
    def fileQuit(self):
        self.close()
 
    def closeEvent(self, ce):
        self.fileQuit()
 
    def about(self):
        QtWidgets.QMessageBox.about(self, "About",
                                    """embedding_in_qt5.py example
Copyright 2005 Florent Rougon, 2006 Darren Dale, 2015 Jens H Nielsen
This program is a simple example of a Qt5 application embedding matplotlib
canvases.
It may be used and modified with no restriction; raw copies as well as
modified versions may be distributed without limitation.
This is modified from the embedding in qt4 example to show the difference
between qt4 and qt5"""
                                )
 
 
qApp = QtWidgets.QApplication(sys.argv)
aw = ApplicationWindow()
aw.setWindowTitle("%s" % progname)
aw.show()
sys.exit(qApp.exec_())
go 复制代码
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QLabel, QPushButton, QWidget, QGroupBox, QHBoxLayout
from PyQt5.QtWidgets import QDesktopWidget
from PyQt5.QtCore import Qt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt

class VisualizationApp(QMainWindow):
    def __init__(self):
        super(VisualizationApp, self).__init__()
        
		# 创建页面
        self.setWindowTitle("可视化应用")
        # 获取屏幕大小
		screen = QDesktopWidget().screenGeometry()
		screen_width, screen_height = screen.width(), screen.height()
		# 计算窗口应该出现在屏幕正中央的位置
		window_width, window_height = 900, 600
		x = (screen_width - window_width) // 2
		y = (screen_height - window_height) // 2
		# 设置窗口的位置和大小
		self.setGeometry(x, y, window_width, window_height)

        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)

        self.layout = QHBoxLayout(self.central_widget)

        # 左侧 groupBox
        self.label_box = QGroupBox("可视化", self)
        self.label_box.setFixedWidth(150)  # 固定宽度
        self.layout.addWidget(self.label_box)

        # 垂直布局
        self.group_layout = QVBoxLayout(self.label_box)
        self.group_layout.setAlignment(Qt.AlignTop)  # 顶格分布

        # 饼图按钮
        self.pie_button = QPushButton("饼图", self)
        self.pie_button.clicked.connect(self.show_pie_chart)
        self.group_layout.addWidget(self.pie_button)

        # 柱状图按钮
        self.bar_button = QPushButton("柱状图", self)
        self.bar_button.clicked.connect(self.show_bar_chart)
        self.group_layout.addWidget(self.bar_button)

        # Matplotlib 白板
        self.figure, self.ax = plt.subplots()
        self.canvas = FigureCanvas(self.figure)
        self.layout.addWidget(self.canvas)

    def show_pie_chart(self):
        data = [30, 40, 20, 10]  # 示例数据
        labels = ['A', 'B', 'C', 'D']  # 示例标签
        self.ax.clear()
        self.ax.pie(data, labels=labels, autopct='%1.1f%%', startangle=90)
        self.ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
        self.canvas.draw()

    def show_bar_chart(self):
        data = [10, 30, 50, 20]  # 示例数据
        categories = ['Category 1', 'Category 2', 'Category 3', 'Category 4']  # 示例类别
        self.ax.clear()
        self.ax.bar(categories, data)
        self.canvas.draw()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = VisualizationApp()
    window.show()
    sys.exit(app.exec_())
相关推荐
界面开发小八哥1 分钟前
更高效的Java 23开发,IntelliJ IDEA助力全面升级
java·开发语言·ide·intellij-idea·开发工具
qystca30 分钟前
洛谷 B3637 最长上升子序列 C语言 记忆化搜索->‘正序‘dp
c语言·开发语言·算法
薯条不要番茄酱30 分钟前
数据结构-8.Java. 七大排序算法(中篇)
java·开发语言·数据结构·后端·算法·排序算法·intellij-idea
今天吃饺子35 分钟前
2024年SCI一区最新改进优化算法——四参数自适应生长优化器,MATLAB代码免费获取...
开发语言·算法·matlab
努力进修40 分钟前
“探索Java List的无限可能:从基础到高级应用“
java·开发语言·list
Ajiang28247353043 小时前
对于C++中stack和queue的认识以及priority_queue的模拟实现
开发语言·c++
幽兰的天空3 小时前
Python 中的模式匹配:深入了解 match 语句
开发语言·python
Theodore_10226 小时前
4 设计模式原则之接口隔离原则
java·开发语言·设计模式·java-ee·接口隔离原则·javaee
----云烟----8 小时前
QT中QString类的各种使用
开发语言·qt
lsx2024068 小时前
SQL SELECT 语句:基础与进阶应用
开发语言