Generate 3D scatter animation using animation.FuncAnimation in Python and matplotlib.pyplot


The result is:

Generate 3D scatter animation using animation.FuncAnimation in Python and matplotlib.pyplot

This page shows how to generate 3D animation of scatter plot using animation.FuncAnimation, python, and matplotlib.pyplot.
By updating the data to plot and using set_3d_properties, you can animate the 3D scatter plot.

See also:

Python Matplotlib Tips: Combine 3D and two 2D animations in one figure using python, matplotlib.pyplot and animation.ArtistAnimation

Example code for python animation: combine 3D and 2D animations in one figure using python, matplotlib.pyplot, and matplotlib.animation.artistanimation

Python Matplotlib Tips: Animate zoomed plot of crowded data by updating xlim using matplotlib.animation.FuncAnimation

This code shows how to animate the zoomed subplot of original crowded subplot using Python and matplotlib.animation.Funcanimation.


In [1]:
import numpy as np
from numpy.random import normal as normal
print('numpy: '+np.version.full_version)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.animation as animation
import matplotlib
print('matplotlib: '+matplotlib.__version__)
numpy: 1.13.3
matplotlib: 2.1.1
In [2]:
nfr = 30 # Number of frames
fps = 10 # Frame per sec
xs = []
ys = []
zs = []
ss = np.arange(1,nfr,0.5)
for s in ss:
    xs.append(normal(50,s,200))
    ys.append(normal(50,s,200))
    zs.append(normal(50,s,200))
In [3]:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
sct, = ax.plot([], [], [], "o", markersize=2)
def update(ifrm, xa, ya, za):
    sct.set_data(xa[ifrm], ya[ifrm])
    sct.set_3d_properties(za[ifrm])
ax.set_xlim(0,100)
ax.set_ylim(0,100)
ax.set_zlim(0,100)
ani = animation.FuncAnimation(fig, update, nfr, fargs=(xs,ys,zs), interval=1000/fps)

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

In [4]:
fn = 'plot_3d_scatter_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 [5]:
import subprocess
cmd = 'magick convert %s.gif -fuzz 5%% -layers Optimize %s_r.gif'%(fn,fn)
subprocess.check_output(cmd)
Out[5]:
b''

Finaly, show the animation in the jupyter notebook.

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