I am new to animating with Matplotlib, and having a little trouble. I would like to create an animation of particle positions, and I would like to display the frame number at each step. I have created sample data at the beginning of my code snippet so the code is self-contained (normally my data is read in from a csv).
The problem - the displayed plot is completely blank. However, if I comment out the return of time_text (i.e. change 'return patches, time_text' to 'return patches') everything works fine. I assume the problem is in how I am updating the time_text, but I am stuck as to how to fix it.
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)