2013-11-14 22 views
4

我想要動畫一個圓形的數組,以便它們隨時間變化。在python/matplotlib中動畫修補程序對象

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

nx = 20 
ny = 20 

fig = plt.figure() 
plt.axis([0,nx,0,ny]) 
ax = plt.gca() 
ax.set_aspect(1) 

for x in range(0,nx): 
    for y in range(0,ny): 
     ax.add_patch(plt.Circle((x+0.5,y+0.5),0.45,color='r')) 

plt.show() 

如何定義的功能init()和動畫(),這樣我可以使用例如產生動畫:

animation.FuncAnimation(fig, animate, initfunc=init,interval=200, blit=True) 
+0

見來評論[這個問題](http://stackoverflow.com/questions/19955073/simple-matplotlib-animation)與一些鏈接例子 –

回答

6

由下面的代碼生成的單個幀的示例你可以改變圓的顏色像這樣的動畫:

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

nx = 20 
ny = 20 

fig = plt.figure() 
plt.axis([0,nx,0,ny]) 
ax = plt.gca() 
ax.set_aspect(1) 

def init(): 
    # initialize an empty list of cirlces 
    return [] 

def animate(i): 
    # draw circles, select to color for the circles based on the input argument i. 
    someColors = ['r', 'b', 'g', 'm', 'y'] 
    patches = [] 
    for x in range(0,nx): 
     for y in range(0,ny): 
      patches.append(ax.add_patch(plt.Circle((x+0.5,y+0.5),0.45,color=someColors[i % 5]))) 
    return patches 

anim = animation.FuncAnimation(fig, animate, init_func=init, 
           frames=10, interval=20, blit=True) 
plt.show() 
+0

太好了:莫莉,非常感謝! – BeMuSeD

+0

@ user2992602,考慮[接受這個答案](http://meta.stackexchange.com/a/5235)如果這有助於你解決你的問題。 – falsetru