2015-01-14 51 views
3

我是新來的動畫與Matplotlib,並有一點麻煩。我想創建一個粒子位置的動畫,並且我想在每一步顯示幀編號。我在代碼片段的開頭創建了示例數據,所以代碼是自包含的(通常我的數據是從csv讀入的)。matplotlib動畫,文本沒有更新

問題 - 顯示的圖是完全空白的。但是,如果我將time_text的返回註釋掉(即將「返回修補程序,time_text」更改爲「返回修補程序」),則一切正常。我認爲問題在於我如何更新time_text,但我堅持如何解決它。


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

box_size = 50 
radius = 1 

df =pd.DataFrame(np.array([np.arange(50),np.arange(50),np.arange(50)]).T, 
          columns = ['x','y','frame']) 

#set up the figure 
fig = plt.figure() 
plt.axis([0,box_size,0,box_size]) 
ax = plt.gca() 
ax.set_aspect(1) 
time_text = ax.text(5, 5,'') 

#initialization of animation, plot empty array of patches 
def init(): 
    time_text.set_text('initial') 
    return [] 

def animate(i): 
    patches = [] 
    #data for this frame only 
    data = df[df.frame == i] 
    time_text.set_text('frame'+str(i)) 
    #plot circles at particle positions 
    for idx,row in data.iterrows(): 
     patches.append(ax.add_patch(plt.Circle((row.x,row.y),radius,color= 'b', 
               alpha = 0.5)))    
    return patches, time_text 

anim = animation.FuncAnimation(fig, animate, init_func=init, repeat = False, 
           frames=int(df.frame.max()), interval=50, 
           blit=True) 
+0

可能[這個問題](https://stackoverflow.com/questions/44594887/how-to-update-plot-title-with-matplotlib-using-animation)可能會有所幫助。 – ImportanceOfBeingErnest

回答

-1

你需要讓你的初始化函數返回pyplot.text對象。您還應該在anim函數的每個調用中啓動要修改的對象。

看看ArtistAnimation,它可能更適合你在做什麼。

爲了避免許多圓圈聚集在畫布上,我寧願更新路徑對象的位置,而不是在每次迭代時追加新的路徑對象。

from matplotlib import pyplot as plt 
import matplotlib.patches as patches 
from matplotlib import animation 
import numpy as np 
import pandas as pd 

box_size = 50 
radius = 1 

df = pd.DataFrame(np.array([np.arange(50),np.arange(50),np.arange(50)]).T, 
          columns = ['x','y','frame']) 

#set up the figure 
fig = plt.figure() 
plt.axis([0,box_size,0,box_size]) 
ax = plt.gca() 
time_text = ax.text(5, 5,'') 

circle = plt.Circle((1.0,1.0), radius,color='b', alpha=0.5, facecolor='orange', lw=2) 


#initialization of animation, plot empty array of patches 
def init(): 
    time_text.set_text('initial') 
    ax.add_patch(circle) 
    return time_text, ax 

def animate(i): 
    #data for this frame only 
    data = df[df.frame == i] 
    time_text.set_text('frame' + str(i)) 

    #plot circles at particle positions 
    for idx,row in data.iterrows(): 
     circle.center = row.x,row.y 

    return time_text, ax 

anim = animation.FuncAnimation(fig, animate, init_func=init, repeat = False, 
           frames=int(df.frame.max()), interval=200, blit=True) 

plt.show() 
+0

@mdriscoll歡迎來到Stack Overflow。注意到我的解決方案引入了一個問題,您將不得不找到一種方法來刪除舊路徑,因爲正在添加新路徑。 –

+0

不幸的是init()函數返回time_text沒有幫助 - 它仍然返回一個沒有動畫的空白圖。 FuncAnimation中有沒有kwarg我錯過了? – mdriscoll

+0

它應該返回至少2個對象,因爲該方法需要迭代。這就是我返回'matplotlib.axes.AxesSubplot'的原因。我發佈的修改後的代碼顯示了在我的兩臺計算機上都有不斷變化的動畫,您是否嘗試過運行它? –