我是Matplotlib动画的新手,遇到了一些问题。我想创建一个粒子位置的动画,并在每个步骤显示帧数。我在代码片段的开头创建了示例数据,因此代码是自包含的(通常我的数据是从CSV文件中读取的)。
问题在于-显示的图表完全空白。但是,如果我注释掉time_text的返回(即将“return patches,time_text”更改为“return patches”),则一切正常。我认为问题在于我如何更新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)