Creating 3D animation using matplotlib

To create a 3D animation using matplotlib, we can take the following steps −

  • Import the required packages. For 3D animation, you need to import Axes3D from mpl_toolkits.mplot3d and matplotlib.animation.
  • Set the figure size and adjust the padding between and around the subplots.
  • Create t, x, y and data points using numpy.
  • Create a new figure or activate an existing figure.
  • Get the instance of 3D axes.
  • Turn off the axes.
  • Plot the lines with data.
  • Create an animation by repeatedly calling a function *animate*.
  • To display the figure, use show() method.


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

def animate(num, data, line):
   colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2',   '#7f7f7f', '#bcbd22', '#17becf']
   line.set_color(colors[num % len(colors)])
   line.set_data(data[0:2, :num])
   line.set_3d_properties(data[2, :num])
   return line

t = np.arange(0, 20, 0.2)
x = np.cos(t) - 1
y = 1 / 2 * (np.cos(2 * t) - 1)
data = np.array([x, y, t])
N = len(t)
fig = plt.figure()
ax = Axes3D(fig)

line, = plt.plot(data[0], data[1], data[2], lw=7, c='red')
line_ani = animation.FuncAnimation(fig, animate, frames=N, fargs=(data, line), interval=50, blit=False)


It will produce the following output