在matplotlib中动态更新图 [英] Dynamically updating plot in matplotlib

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

问题描述

我正在用Python开发一个应用程序,该应用程序从串行端口收集数据并针对到达时间绘制收集的数据图.数据的到达时间不确定.我希望在收到数据时更新绘图.我搜索了如何执行此操作,发现了两种方法:

I am making an application in Python which collects data from a serial port and plots a graph of the collected data against arrival time. The time of arrival for the data is uncertain. I want the plot to be updated when data is received. I searched on how to do this and found two methods:

  1. 清除图并再次绘制所有点的图.
  2. 通过在特定时间间隔后对其进行更改来对图进行动画处理.

我不喜欢第一个程序,因为该程序会运行很长时间(例如一天),并且会收集数据,因此重新绘制绘图会非常缓慢. 第二种方法也不可取,因为数据的到达时间不确定,我希望绘图仅在接收到数据时进行更新.

I do not prefer the first one as the program runs and collects data for a long time (a day for example), and redrawing the plot will be pretty slow. The second one is also not preferable as time of arrival of data is uncertain and I want the plot to update only when the data is received.

有没有一种方法可以仅在接收到数据时通过添加更多点来更新图?

Is there a way in which I can update the plot just by adding more points to it only when the data is received?

推荐答案

有没有一种方法可以通过向图上添加更多点来更新图...

matplotlib中有多种动画数据的方式,具体取决于您使用的版本.您是否看到过 matplotlib食谱示例?另外,请在matplotlib文档中查看更现代的动画示例.最后,动画API 定义了一个函数FuncAnimation ,该动画会及时对函数进行动画处理.该功能可能只是您用来获取数据的功能.

There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the matplotlib cookbook examples? Also, check out the more modern animation examples in the matplotlib documentation. Finally, the animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data.

每种方法基本上都设置要绘制对象的data属性,因此不需要清除屏幕或图形. data属性可以简单地扩展,因此您可以保留先前的点,而只需继续添加到线条(或图像或所绘制的内容)中即可.

Each method basically sets the data property of the object being drawn, so doesn't require clearing the screen or figure. The data property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).

假设您说数据到达时间不确定,那么最好的选择可能就是执行以下操作:

Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:

import matplotlib.pyplot as plt
import numpy

hl, = plt.plot([], [])

def update_line(hl, new_data):
    hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
    hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
    plt.draw()

然后,当您从串行端口接收数据时,只需调用update_line.

Then when you receive data from the serial port just call update_line.

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

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