I'm trying to plot the movement of particles with pyplot. The problem is that I can't figure out how to create the animation.
Here is the notebook : http://nbviewer.ipython.org/gist/lhk/949c7bf7007445033fd9
Apparently the update function doesn't work properly, but the error message is too cryptic for me. What do I need to change ?
Do you have a good tutorial on animation with pyplot ?
As @s0upa1t comments you should have figure handle as the first argument to animation. The criptic error results from animation expecting a fig
object, which has attribute canvas
but instead gets scatter
, a PathCollection
object, which does not. As a minimal example of animation in the form you want, consider,
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
dt = 0.005
n=20
L = 1
particles=np.zeros(n,dtype=[("position", float , 2),
("velocity", float ,2),
("force", float ,2),
("size", float , 1)])
particles["position"]=np.random.uniform(0,L,(n,2));
particles["velocity"]=np.zeros((n,2));
particles["size"]=0.5*np.ones(n);
fig = plt.figure(figsize=(7,7))
ax = plt.axes(xlim=(0,L),ylim=(0,L))
scatter=ax.scatter(particles["position"][:,0], particles["position"][:,1])
def update(frame_number):
particles["force"]=np.random.uniform(-2,2.,(n,2));
particles["velocity"] = particles["velocity"] + particles["force"]*dt
particles["position"] = particles["position"] + particles["velocity"]*dt
particles["position"] = particles["position"]%L
scatter.set_offsets(particles["position"])
return scatter,
anim = FuncAnimation(fig, update, interval=10)
plt.show()
There are many good animation tutorials, however the answer here is particularly nice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With