Skip to content

Instantly share code, notes, and snippets.

@stefanv
Created January 24, 2012 22:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stefanv/1673002 to your computer and use it in GitHub Desktop.
Save stefanv/1673002 to your computer and use it in GitHub Desktop.
Random walk example
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(-10, 10)
ax.set_aspect(1)
x = [0]
y = [0]
line, = ax.plot(x, y, '-o', color='0.8', markerfacecolor='0', marker='.')
def update(frame, x, y):
# Choose a random direction
d = np.random.random() * 2 * np.pi
# Add a new step
x.append(x[-1] + np.cos(d))
y.append(y[-1] + np.sin(d))
# Only show the last 500 steps
if len(x) > 500:
x.pop(0)
y.pop(0)
# Update the line
line.set_xdata(x)
line.set_ydata(y)
ax.set_xlim(min(x), max(x))
ax.set_ylim(min(y), max(y))
return line,
ani = animation.FuncAnimation(fig, update, fargs=(x, y), interval=10)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment