06a: Using Matplotlib to Create Animation¶
This notebooks shows how to create an animation that will run and play inside a notebook. The animation can also be written to a video file.
[1]:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
[2]:
def get_y(x, a, b, c, d):
y = a * np.sin(b * x + c) + d
return y
fig, ax = plt.subplots()
x = np.linspace(0, 2 * np.pi, 100)
a = 1
b = 1
c = 0
d = 0
y0 = get_y(x, a, b, c, d)
line = ax.plot(x, y0, 'b-', clip_on=False)
line = line[0]
xd = np.pi
yd = get_y(xd, a, b, c, d)
dot = ax.plot(xd, yd, 'ro', ms=10, clip_on=False)
dot = dot[0]
ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-a, a)
frames = 50
def update(i):
dt = 2 * np.pi / frames
c = i * dt
# for each frame, update the data stored on each artist.
y = get_y(x, a, b, c, d)
line.set_xdata(x)
line.set_ydata(y)
yd = get_y(xd, a, b, c, d)
dot.set_ydata([yd])
return line,
ani = animation.FuncAnimation(fig=fig, func=update, frames=frames)
plt.close()
from IPython.display import HTML
HTML(ani.to_jshtml())
[2]:
[3]:
# the following can be used to save the animation to a file
# ext = "mp4" # mac mp4
ext = "avi" # windows avi
ani.save(f"sin_animation.{ext}")
[ ]: