如何在数据文件更改时动态更新我的 matplotlib 图? [英] How can I dynamically update my matplotlib figure as the data file changes?

查看:64
本文介绍了如何在数据文件更改时动态更新我的 matplotlib 图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 python 脚本,它读入一个数据文件并使用 matplotlib 库显示一个带有四个图的图形.数据文件每隔几秒钟更新一次,因为它是同时运行的不同软件的输出文件.我希望我的 matplotlib 图中的四个图每 20 秒使用更新的数据文件刷新自己.我的实现方式如下:

I have a python script that reads in a data file and displays one figure with four plots using the matplotlib library. The data file is being updated every few seconds since it is an output file for a different piece of software that is running concurrently. I would like the four plots in my matplotlib figure to refresh themselves using the updated data file every 20 seconds. The way I've implemented this is as follows:

import pylab as pl
import time

pl.ion()
fig = pl.figure()
while True:
    f = open('data.out', 'rb')
    #code to parse data and plot four charts
    ax = fig.add_subplot(2,2,1)
    #...
    ax = fig.add_subplot(2,2,4)
    #...
    pl.draw()
    time.sleep(20)

这有效,但我失去了缩放和平移按钮的功能,如果调用 pl.show(),这些按钮通常会起作用.这不是最佳的.但是,如果 pl.show() 替换为 pl.draw(),脚本将不再更新绘图.有没有一种方法可以动态更新图而不会完全失去缩放/平移功能?

This works, but I lose functionality of the zoom and pan buttons which normally work if pl.show() is called. This is not optimal. However, if pl.show() is substituted for pl.draw(), the script no longer updates the plots. Is there a way to dynamically update a plot without completely losing the zoom/pan functionality?

推荐答案

您的代码有点含糊,无法知道正在发生什么.

Your code is a little too vague to know what is going on.

我可以提供:如果一次创建子图,保存所有轴对象,然后调用show(),则应该保留正常功能.

I can offer this: You should retain normal functionality if you create your subplots once, saving all the axes objects and then calling show().

对这些子图的后续更改可以这样完成:

Subsequent changes to those subplots could be done like this:

#inside while loop
for i in #subplotlist
    ax[i].clear()    #ax[i] is the axis object of the i'th subplot
    ax[i].plot(#plotstuff)
    ax[i].draw()

如果您愿意,可以手动添加用于缩放和平移的工具栏.

The toolbar for zooming and panning can be added by hand if you so desire.

这篇关于如何在数据文件更改时动态更新我的 matplotlib 图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆