5

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 ?

2
  • possible duplicate of why is plotting with Matplotlib so slow? Commented Aug 28, 2015 at 10:21
  • FuncAnimation takes fig as a first argument, not LineCollection. Btw, search SO for articles on topic - there are a lot of them. Commented Aug 28, 2015 at 10:22

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.