栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

动态刷新matplotlib图片

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

动态刷新matplotlib图片

用matplotlib动态刷新曲线折现图

动态展示折线图,每0.02秒刷新一次数据,动态展示图片

# file name: plot.py
# author: yue
# datetime: 2022/6/4 14:29
from time import sleep
from threading import Thread
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button


# 自定义类,用来封装两个按钮的单击事件处理函数
class ButtonHandler:
    def __init__(self):
        self.flag = True
        self.range_s, self.range_e, self.range_step = 0, 1, 0.005

    # 线程函数,用来更新数据并重新绘制图形
    def threadStart(self):
        while self.flag:
            sleep(0.02)
            self.range_s += self.range_step
            self.range_e += self.range_step
            t = np.arange(self.range_s, self.range_e, self.range_step)
            ydata = np.sin(4 * np.pi * t)
            # 更新数据
            l.set_xdata(t - t[0])
            l.set_ydata(ydata)
            # 重新绘制图形
            plt.draw()

    def Start(self, event):
        print('click start!')
        self.flag = True
        # 创建并启动新线程
        t_ = Thread(target=self.threadStart)
        t_.start()

    def Stop(self, event):
        self.flag = False


if __name__ == '__main__':
    fig, ax = plt.subplots()
    # 设置图形显示位置
    plt.subplots_adjust(bottom=0.2)
    # 实验数据
    range_start, range_end, range_step = 0, 1, 0.005
    t = np.arange(range_start, range_end, range_step)
    s = np.sin(4 * np.pi * t)
    l, = plt.plot(t, s, lw=2)

    callback = ButtonHandler()
    # 创建按钮并设置单击事件处理函数
    axprev = plt.axes([0.81, 0.05, 0.1, 0.075])
    bprev = Button(axprev, 'Stop')
    bprev.on_clicked(callback.Stop)
    axnext = plt.axes([0.7, 0.05, 0.1, 0.075])
    bnext = Button(axnext, 'Start')
    bnext.on_clicked(callback.Start)
    plt.show()

效果图

⚠️注意:运行这个文件,最好不要在PyCharm 中点击run来运行,因为PyCharm展示的是png图片,无法点击Start按钮。
请直接在终端运行: python plot.py

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/949884.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号