python动态绘图并保留之前绘图_python - 在matplotlib中动态更新绘图

时间:2025-05-05 20:27:17

python - 在matplotlib中动态更新绘图

我在Python中创建一个应用程序,它从串行端口收集数据,并根据到达时间绘制收集数据的图表。 数据的到达时间不确定。 我希望在收到数据时更新绘图。 我搜索了如何做到这一点,并找到了两种方法:

清除绘图并再次绘制所有点的绘图。

通过在特定间隔后更改它来为动画设置动画。

我不喜欢第一个,因为程序运行并收集数据很长一段时间(例如一天),重绘绘图将非常慢。第二个也不是优选的,因为数据的到达时间是不确定的,并且我希望仅在接收到数据时更新图。

有没有办法只通过在收到数据时添加更多的点来更新图表?

4个解决方案

111 votes

有没有办法我可以通过添加更多的点[s]来更新图表...

在matplotlib中有很多种动画数据的方法,具体取决于您拥有的版本。 你看过matplotlib食谱的例子吗? 另外,请查看matplotlib文档中更现代的动画示例。 最后,动画API定义了一个函数FuncAnimation,它可以及时激活一个函数。 此功能可能只是您用于获取数据的功能。

每种方法基本上都设置了绘制对象的属性,因此不需要清除屏幕或图形。 data属性可以简单地扩展,因此您可以保留以前的点并继续添加到您的线(或图像或您正在绘制的任何内容)。

鉴于您说您的数据到达时间不确定,您最好的选择可能只是做以下事情:

import as plt

import numpy

hl, = ([], [])

def update_line(hl, new_data):

hl.set_xdata((hl.get_xdata(), new_data))

hl.set_ydata((hl.get_ydata(), new_data))

()

然后,当您从串口接收数据时,请致电update_line。

Chris answered 2019-08-10T08:05:48Z

31 votes

为了在没有FuncAnimation的情况下执行此操作(例如,您希望在生成绘图时执行代码的其他部分,或者您希望同时更新多个绘图),单独调用draw不会产生绘图(至少与 qt后端)。

以下为我工作:

import as plt

()

class DynamicUpdate():

#Suppose we know the x range

min_x = 0

max_x = 10

def on_launch(self):

#Set up plot

, = ()

, = ([],[], 'o')

#Autoscale on unknown axis and known lims on the other

.set_autoscaley_on(True)

.set_xlim(self.min_x, self.max_x)

#Other stuff

()

...

def on_running(self, xdata, ydata):

#Update data (with the new _and_ the old points)

.set_xdata(xdata)

.set_ydata(ydata)

#Need both of these in order to rescale

()

.autoscale_view()

#We need to draw *and* flush

()

.flush_events()

#Example

def __call__(self):

import numpy as np

import time

self.on_launch()

xdata = []

ydata = []

for x in (0,10,0.5):

(x)

((-x**2)+10*(-(x-7)**2))

self.on_running(xdata, ydata)

(1)

return xdata, ydata

d = DynamicUpdate()

d()

Zah answered 2019-08-10T08:06:16Z

2 votes

我知道我迟到了回答这个问题,但对于你的问题,你可以查看"操纵杆" 包。 我设计它用于绘制来自串行端口的数据流,但它适用于任何流。 它还允许交互式文本记录或图像绘图(除了图形绘图)。无需在单独的线程中执行您自己的循环,包就可以处理它,只需提供您希望的更新频率。 此外,终端在绘图时仍可用于监控命令。请参阅[/ceyzeriat/joystick/]或[/pypi/joystick](使用pip install操纵杆进行安装)

只需用下面代码中从串口读取的实际数据点替换():

import joystick as jk

import numpy as np

import time

class test():

# initialize the infinite loop decorator

_infinite_loop = jk.deco_infinite_loop()

def _init(self, *args, **kwargs):

"""

Function called at initialization, see the doc

"""

self._t0 = () # initialize time

= ([self._t0]) # time x-axis

= ([0.0]) # fake data y-axis

# create a graph frame

= self.add_frame((name="test", size=(500, 500), pos=(50, 50), fmt="go-", xnpts=10000, xnptsmax=10000, xylim=(None, None, 0, 1)))

@_infinite_loop(wait_time=0.2)

def _generate_data(self): # function looped every 0.2 second to read or produce data

"""

Loop starting with the simulation start, getting data and

pushing it to the graph every 0.2 seconds

"""

# concatenate data on the time x-axis

= .add_datapoint(, (), xnptsmax=)

# concatenate data on the fake data y-axis

= .add_datapoint(, (), xnptsmax=)

.set_xydata(t, )

t = test()

()

()

Guillaume S answered 2019-08-10T08:06:54Z

0 votes

这是一种允许在绘制一定数量的点后删除点的方法:

import as plt

# generate axes object

ax = ()

# set limits

(0,10)

(0,10)

for i in range(10):

# add something to axes

([i], [i])

([i], [i+1], 'rx')

# draw the plot

()

(0.01) #is necessary for the plot to update for some reason

# start removing points if you don't want all shown

if i>2:

[0].remove()

[0].remove()

NDM answered 2019-08-10T08:07:19Z