Animate 3D wireframe using animation.FuncAnimation in Python and maptlotlib.pyplot


The result is:

Animate 3D wireframe using animation.FuncAnimation in Python and maptlotlib.pyplot

This page shows how to animate 3D wireframe figure using animation.FuncAnimation in Python and matplotlib.pyplot.

See also:

Python Matplotlib Tips: Generate animation of 3D surface plot using plot_surface and animation.FuncAnimation in Python and matplotlib.pyplot

This page shows how to generate an animation of 3D surface plot using plot_surface and animation.FuncAnimation in python and matplotlib.pyplot.

Python Matplotlib Tips: Rotate azimuth angle and animate 3d plot_surface using Python and matplotlib.pyplot

This page shows how to generate animation with rotating azimuth angle in the 3D surface plot using python, matplotlib.pyplot, and matplotlib.animation.FuncAnimation.


This code is based on the following matplotlib tutorial:

In [1]:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
print('numpy: '+np.version.full_version)
import matplotlib.animation as animation
import matplotlib
print('matplotlib: '+matplotlib.__version__)
%matplotlib inline
numpy: 1.15.4
matplotlib: 3.0.1
In [2]:
Nfrm = 10
fps = 10
In [3]:
def generate(X, Y, phi):
    '''
    Generates Z data for the points in the X, Y meshgrid and parameter phi.
    '''
    R = 1 - np.sqrt(X**2 + Y**2)
    return np.cos(2 * np.pi * X + phi) * R
In [4]:
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111, projection='3d')

# Make the X, Y meshgrid.
xs = np.linspace(-1, 1, 50)
ys = np.linspace(-1, 1, 50)
X, Y = np.meshgrid(xs, ys)

# Set the z axis limits so they aren't recalculated each frame.
ax.set_zlim(-1, 1)

# Begin plotting.
wframe = None
Z = generate(X, Y, 0)
def update(idx):
    phi=phis[idx]
    global wframe
    # If a line collection is already remove it before drawing.
    if wframe:
        ax.collections.remove(wframe)

    # Plot the new wireframe and pause briefly before continuing.
    Z = generate(X, Y, phi)
    wframe = ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1, color='k', linewidth=0.5)
phis = np.linspace(0, 180. / np.pi, 100)
ani = animation.FuncAnimation(fig, update, Nfrm, interval=1000/fps)

Save the animation in the mp4 and gif format using ffmpeg and imagemagick, respectively.

In [5]:
fn = 'plot_wireframe_funcanimation'
ani.save(fn+'.mp4',writer='ffmpeg',fps=fps)
ani.save(fn+'.gif',writer='imagemagick',fps=fps)

Reduce the size of the GIF file using imagemagick.

In [6]:
import subprocess
cmd = 'magick convert %s.gif -fuzz 5%% -layers Optimize %s_r.gif'%(fn,fn)
subprocess.check_output(cmd, shell=True)
Out[6]:
b''

Finaly, show the animation in the jupyter notebook.

In [7]:
plt.rcParams['animation.html'] = 'html5'
ani
Out[7]: