You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用plt.pause()实现一维时序数据的动态延时可视化?

解决动态一维图表展示问题

先搞懂plt.pause()的作用

plt.pause(seconds)核心做两件事:

  • 暂停程序执行指定秒数
  • 强制刷新matplotlib绘图窗口,把当前所有绘图操作的结果实时显示出来

你原来的代码把它放在循环外面,等所有曲线都画完才触发一次暂停,自然看不到逐个时刻动态展示的效果。

修改后的代码

要实现逐个时刻的动态可视化,需要开启matplotlib的交互模式,每次循环只绘制当前时刻的曲线,刷新后暂停:

import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.simplefilter(action='ignore')

path_temp = '/mnt/sd-card/Dropbox/Documents/exjobb/temp/'
ext = '.csv'
df = pd.read_csv(path_temp+'df_master'+ext)
loggers3 = ['20796674', '15617', '15592', '15606', '15543', '20796679', '15610', '15566', '15565', '20796630']
timestamp = ['2022-03-13 00:00:00', '2022-03-13 01:00:00', '2022-03-13 02:00:00', '2022-03-13 03:00:00', '2022-03-13 04:00:00', '2022-03-13 05:00:00', '2022-03-13 06:00:00', '2022-03-13 07:00:00', '2022-03-13 08:00:00', '2022-03-13 09:00:00', '2022-03-13 10:00:00', '2022-03-13 11:00:00', '2022-03-13 12:00:00', '2022-03-13 13:00:00', '2022-03-13 14:00:00', '2022-03-13 15:00:00', '2022-03-13 16:00:00', '2022-03-13 17:00:00', '2022-03-13 18:00:00', '2022-03-13 19:00:00', '2022-03-13 20:00:00', '2022-03-13 21:00:00', '2022-03-13 22:00:00', '2022-03-13 23:00:00']
target_column = 'Diff '
target_name = 'Diff '

# 提前处理列名,避免循环内重复计算
colnames = [column for column in df.columns if target_column in column] 
del colnames[10:12]
column_names = [target_name+i for i in loggers3]

# 开启交互模式,允许动态更新图表
plt.ion()
fig, ax = plt.subplots()

for time in timestamp:
    # 获取当前时刻的目标数据
    data = df.loc[df['TIMESTAMP'] == time]
    pressures = data[column_names].iloc[0]
    
    # 清空当前坐标轴,避免曲线叠加
    ax.clear()
    # 绘制当前时刻的一维曲线
    ax.plot(colnames, pressures.values, '-o', label=time)
    # 配置图表元素
    ax.legend()
    ax.set_title(f"数据实时展示 - {time}")
    ax.set_xlabel("Logger ID")
    ax.set_ylabel(target_name)
    
    # 刷新窗口并暂停(可调整暂停时长,比如改成1秒)
    plt.pause(0.5)

# 循环结束后关闭交互模式,保持窗口打开
plt.ioff()
plt.show()

关键修改说明

  • 用plt.ion()开启交互模式,这是动态更新图表的前提
  • 提前生成colnames和column_names,减少循环内的重复计算
  • 每次循环用ax.clear()清空之前的曲线,确保只显示当前时刻的数据
  • 将plt.pause()移入循环内部,实现绘制-刷新-暂停的动态流程
  • 循环结束后用plt.ioff()关闭交互模式,避免窗口自动关闭

内容的提问来源于stack exchange,提问作者Tobias Bowley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 19:39:23