Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
52867 views
1
import numpy as np
2
from matplotlib import pyplot as plt
3
from matplotlib import animation
4
from JSAnimation import IPython_display
5
6
def basic_animation(frames=100, interval=30):
7
"""Plot a basic sine wave with oscillating amplitude"""
8
fig = plt.figure()
9
ax = plt.axes(xlim=(0, 10), ylim=(-2, 2))
10
line, = ax.plot([], [], lw=2)
11
12
x = np.linspace(0, 10, 1000)
13
14
def init():
15
line.set_data([], [])
16
return line,
17
18
def animate(i):
19
y = np.cos(i * 0.02 * np.pi) * np.sin(x - i * 0.02 * np.pi)
20
line.set_data(x, y)
21
return line,
22
23
return animation.FuncAnimation(fig, animate, init_func=init,
24
frames=frames, interval=interval)
25
26
27
def lorenz_animation(N_trajectories=20, rseed=1, frames=200, interval=30):
28
"""Plot a 3D visualization of the dynamics of the Lorenz system"""
29
from scipy import integrate
30
from mpl_toolkits.mplot3d import Axes3D
31
from matplotlib.colors import cnames
32
33
def lorentz_deriv(coords, t0, sigma=10., beta=8./3, rho=28.0):
34
"""Compute the time-derivative of a Lorentz system."""
35
x, y, z = coords
36
return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
37
38
# Choose random starting points, uniformly distributed from -15 to 15
39
np.random.seed(rseed)
40
x0 = -15 + 30 * np.random.random((N_trajectories, 3))
41
42
# Solve for the trajectories
43
t = np.linspace(0, 2, 500)
44
x_t = np.asarray([integrate.odeint(lorentz_deriv, x0i, t)
45
for x0i in x0])
46
47
# Set up figure & 3D axis for animation
48
fig = plt.figure()
49
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
50
ax.axis('off')
51
52
# choose a different color for each trajectory
53
colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))
54
55
# set up lines and points
56
lines = sum([ax.plot([], [], [], '-', c=c)
57
for c in colors], [])
58
pts = sum([ax.plot([], [], [], 'o', c=c, ms=4)
59
for c in colors], [])
60
61
# prepare the axes limits
62
ax.set_xlim((-25, 25))
63
ax.set_ylim((-35, 35))
64
ax.set_zlim((5, 55))
65
66
# set point-of-view: specified by (altitude degrees, azimuth degrees)
67
ax.view_init(30, 0)
68
69
# initialization function: plot the background of each frame
70
def init():
71
for line, pt in zip(lines, pts):
72
line.set_data([], [])
73
line.set_3d_properties([])
74
75
pt.set_data([], [])
76
pt.set_3d_properties([])
77
return lines + pts
78
79
# animation function: called sequentially
80
def animate(i):
81
# we'll step two time-steps per frame. This leads to nice results.
82
i = (2 * i) % x_t.shape[1]
83
84
for line, pt, xi in zip(lines, pts, x_t):
85
x, y, z = xi[:i + 1].T
86
line.set_data(x, y)
87
line.set_3d_properties(z)
88
89
pt.set_data(x[-1:], y[-1:])
90
pt.set_3d_properties(z[-1:])
91
92
ax.view_init(30, 0.3 * i)
93
fig.canvas.draw()
94
return lines + pts
95
96
return animation.FuncAnimation(fig, animate, init_func=init,
97
frames=frames, interval=interval)
98
99