Skip to content Skip to sidebar Skip to footer

Animate A Scatterplot With Pyplot

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/gis

Solution 1:

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])

defupdate(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.

Post a Comment for "Animate A Scatterplot With Pyplot"