2011-12-26 30 views
0

您好所有和圣诞的帮助,matplotlib [巨蟒]:在解释动画例子

可能有人请解释一下我的代码下面的示例是如何工作的(http://matplotlib.sourceforge.net/examples/animation /random_data.html)?

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 


timeline = [1,2,3,4,5,6,7,8,9,10] ; 
metric = [10,20,30,40,50,60,70,80,90,100] ; 

fig = plt.figure() 
window = fig.add_subplot(111) 
line, = window.plot(np.random.rand(10)) 

def update(data): 
    line.set_ydata(data) 
    return line, 

def data_gen(): 
    while True: 
     yield np.random.rand(10) 


ani = animation.FuncAnimation(fig, update, data_gen, interval=5*1000) 
plt.show() 

特别是,我想用list(“metric”)来更新列表。 问题是,如果我没有弄错,FuncAnimation使用的是生成器,但是,我怎样才能使它工作?

谢谢。

回答

1

您可以使用任何迭代器(而不仅仅是一个生成器)来馈送FuncAnimationFrom docs

类matplotlib.animation.FuncAnimation(无花果,FUNC,帧=无, 的init_func =无,fargs =无,save_count =无,** kwargs)

通过重复地使一个动画调用函数func,在fargs中传入 (可选)参数。 帧可以是发生器,可迭代的, 或多个帧。 init_func是一个函数,用于绘制一个明确的框架。如果没有给出,将使用 帧序列中第一项的绘制结果。

因此,与列表中的equivalen代码可能是:

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

start = [1, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0] 

metric =[[0.03, 0.86, 0.65, 0.34, 0.34, 0.02, 0.22, 0.74, 0.66, 0.65], 
     [0.43, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0.55], 
     [0.66, 0.75, 0.01, 0.94, 0.72, 0.77, 0.20, 0.66, 0.81, 0.52] 
     ] 

fig = plt.figure() 
window = fig.add_subplot(111) 
line, = window.plot(start) 

def update(data): 
    line.set_ydata(data) 
    return line, 

ani = animation.FuncAnimation(fig, update, metric, interval=2*1000) 
plt.show()