Matplotlib数据更新的实时绘图



我想实时绘制仪器采集的一些数据。以下工作(以随机数据为例(:

import matplotlib.pyplot as plt 
from matplotlib.animation import FuncAnimation
import random
from itertools import count
import time
%matplotlib qt  
fields, volts = [], []
index = count()
def animate(i):    
global fields, volts
fields.append(next(index))
volts.append(random.randint(0, 5))
plt.cla()
plt.plot(fields, volts)
fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot(111)
ani = FuncAnimation(fig, animate, 1000)
plt.show()

但我需要在FuncAnimation的外部的数据更新,在它自己的循环中。我相信它可以工作,但下面的代码只是打开窗口,直到我停止程序才更新它:

fields, volts = [], []
index = count()
def animate(i):    
global fields, volts

plt.cla()
plt.plot(fields, volts)
fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot(111)
ani = FuncAnimation(fig, animate, 1000)
plt.show()
while (True):
time.sleep(1)
fields.append(next(index))
volts.append(random.randint(0, 5))

试试看,FuncAnimation会定期调用animate,这样您就可以将append语句转移到该循环中,还可以使用interval关键字参数控制间隔。

fields, volts = [], [] 
index =iter(range(20)) 
from numpy import random 

def animate(i):     
global fields, volts 
fields.append(len(volts)) 
volts.append(random.randint(0,5)) 
plt.cla() 
plt.plot(fields, volts, c='c') 

fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot(111)
ani = FuncAnimation(fig, animate, frames=20, interval=1000)
plt.show()

最新更新