2014-11-21 41 views
1

我有一些困難,試圖讓FuncAnimation在Matplotlib中工作。這是我想要實現的。我有linexdata和lineydataFuncAnimation Matplotlib難度

linexdata = [[0, 0.96663913603170604, 1.8304227404767459], [0, 0.96734736607357541, 1.8288493988572816], [0, 0.96802166208581697, 1.8272797290389486], [0, 0.96866363556090329, 1.8257115495669918]] 
lineydata = [[0, 0.25614211034477896, 0.76000507255964045], [0, 0.253454282564955, 0.76120840368022669], [0, 0.25086662139992305, 0.76240896996548169], [0, 0.24837624915022258, 0.76361296474589158]] 

2名列表的實際長度大約是2000年。我只是出了幾個數據點來說明什麼,我試圖做的。

我想顯示linedata的動畫。

這裏是我的代碼:

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

fig = plt.figure(figsize=(7,7)); 
ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(-0.5,3), ylim=(-0.5,3)) 
ax.grid() 
line, = ax.plot([], [], 'o-', lw=2) 
line.set_data([], []); 

def init(): 
    line.set_data([], []) 
    return line, 

def animate(i): 
    line.set_data(linexdata[i] ,lineydata[i]); 
    return line, 

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20) 

plt.show() 

輸出情節是空的。我以某種方式不能得到這個工作,主要是因爲我不知道如何使用FuncAnimation,我無法弄清楚錯誤在哪裏。任何幫助表示讚賞。

謝謝。

回答

1

這裏發生的是FuncAnimation遞歸調用您的animate函數。每次它將用於索引數據的變量i遞增1。遞歸的數量在調用函數時由參數「frames」控制。

由於您的linexdata列表只包含4個列表,並且考慮到您使用frames=200調用了Funcanimation,所以在前4次調用之後,python會崩潰並返回IndexError。根據您的數據大小調整幀數是解決您的問題的方法。

你看不到任何東西的原因(即使不是4條第一行)是因爲它讓我們快速地看到任何東西。 interval=20意味着它在兩次調用之間變爲20毫秒到animate。例如,將這個數字增加到500會讓你看到會發生什麼。 (爲了清楚起見,我可以自由地修改你的列表,使兩幀之間的變化清晰可見)。

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

linexdata = [[0, 0.96663913603170604, 1.8304227404767459], [0, 0.96734736607357541, 2.8288493988572816], [0, 0.96802166208581697, 3.8272797290389486], [0, 0.96866363556090329, 4.8257115495669918]] 
lineydata = [[0, 0.25614211034477896, 0.76000507255964045], [0, 0.253454282564955, 0.76120840368022669], [0, 0.25086662139992305, 0.76240896996548169], [0, 0.24837624915022258, 0.76361296474589158]] 


fig = plt.figure(figsize=(7,7)); 
ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(-0.5,3), ylim=(-0.5,3)) 
ax.grid() 
line, = ax.plot([], [], 'o-', lw=2) 
line.set_data([], []); 

def init(): 
    line.set_data([], []) 
    return line, 

def animate(i): 
    line.set_data(linexdata[i] ,lineydata[i]); 
    return line, 


anim = animation.FuncAnimation(fig, animate, init_func=init, frames=4, interval=500) 

plt.show()