问题描述
我正在用 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:
- 清除绘图并再次使用所有点重新绘制绘图.
- 通过在特定时间间隔后更改情节来制作动画.
我不喜欢第一个,因为程序运行并收集数据很长时间(例如一天),重绘绘图会很慢.第二个也不可取,因为数据的到达时间不确定,我希望绘图仅在收到数据时更新.
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 中动态更新绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!