Draw 3D line animation using Python Matplotlib.ArtistAnimation


The result is:

Draw 3D line animation using Python Matplotlib.ArtistAnimation

This page shows how to draw 3D line animation using python & matplotlib. Note that you must install ffmpeg and imagemagick to properly display the result.
This code is based on following web sites:
In [1]:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
from IPython.display import HTML
Draw the animation
In [2]:
# Attaching 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)

# Lines to plot in 3D
t = np.linspace(-2 * np.pi, 2 * np.pi, 50)
x1, y1, z1 = np.cos(t), np.sin(t), t / t.max()
x2, y2, z2 = t / t.max(), np.cos(t), np.sin(t)

ax.set_xlim(-1.1, 1.1)
ax.set_ylim(-1.1, 1.1)
ax.set_zlim(-1.1, 1.1)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.rcParams['animation.html'] = 'html5'

# stack the plots
lns = []
for i in range(len(t)):
    ln1, = ax.plot(x1[:i], y1[:i], z1[:i], 'o-', color='steelblue')
    ln2, = ax.plot(x2[:i], y2[:i], z2[:i], 'o-', color='darkorange')
    lns.append([ln1, ln2])

line_ani = animation.ArtistAnimation(fig, lns, interval=100, blit=True)

# The empty figure shown below is unknown.
# Does anyone know how to delete this?
Then display the result
In [3]:
line_ani
Out[3]:
Save the figure
In [4]:
line_ani.save('line_animation_3d_artistanimation.mp4',writer='ffmpeg',fps=1000/100)
line_ani.save('line_animation_3d_artistanimation.gif',writer='imagemagick',fps=1000/100)