我是新來的動畫與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)
可能[這個問題](https://stackoverflow.com/questions/44594887/how-to-update-plot-title-with-matplotlib-using-animation)可能會有所幫助。 – ImportanceOfBeingErnest