I would like to model basic crowd movement with python. I want to show an animation. I have made the following program to test it with matplotlib :
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
#size of the crowd
N = 100
def gen_data():
""" init position and speed of each people """
x = y = np.zeros(N)
theta = np.random.random(N) * 360 / (2 * np.pi)
v0 = 0.1
vx, vy = v0 * np.cos(theta), v0 * np.sin(theta)
return np.array([x, y, vx, vy]).T
def init():
for line in lines:
line.set_data([],[])
return line,
def update_lines(i, lines, data):
for d, line in zip(data, lines):
d[0:2] += d[2:4]
if abs(d[0]) > 5: d[2] *= -1
if abs(d[1]) > 5: d[3] *= -1
line.set_data(d[0] ,d[1])
return lines
fig = plt.figure()
ax = plt.axes(xlim=(-5,5),ylim=(-5,5))
lines = [plt.plot([],[], 'ko')[0] for i in range(N)]
data = gen_data()
anim = animation.FuncAnimation(fig, update_lines, init_func=init, fargs=(lines, data), interval=10, blit=True)
plt.show()
Even for N=100, the animation is slow... Is there something I can do to speed it up with mathplotlib ? Is matplotlib the best graphic tool to make thins kind of animation with python ? If no, what would it be ?
Here are 3 things you can do to make the animation faster:
N
calls toplt.plot
with one call toplt.scatter
.Replace the
for-loop
inupdate
with assignments which modify whole slices ofdata
at once:Reduce
interval=10
tointerval=0
.