Animate zoomed plot of crowded data by updating xlim using matplotlib.animation.FuncAnimation


The result is:
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.
You can easily do it by updateing xlim of zoomed subplot.
See also:

Python Matplotlib Tips: Solve and animate single pendulum using scipy.odeint and matplotlib.animation.ArtistAnimation

Example of scipy.odeint function which solves the motion of the single pendulum. The result is converted to the animation using ArtistAnimation function.


In [1]:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
%matplotlib inline

In this animation, some narrow range in the upper subplot is expanded and shown in lower subplot. The vertical bars in upper subplot shows the range to expand.

In [2]:
NUMFRAMES = 200
# create a figure and initialize the data
fig = plt.figure(facecolor='w',figsize=(7,4))
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
xs = np.linspace(0,NUMFRAMES/5,10000)
ys = np.sin(xs**2)

ax1.plot(xs, ys, 'r-')
l1, = ax1.plot([0,0],[-1,1],'b-') # line 1 which shows the start point to expand data
l2, = ax1.plot([0,0],[-1,1],'b-') # line 2 which shows the end point to expand data
ax2.plot(xs, ys, 'r-')


def animate(i,l1,l2):
    # update the start/end point, and the data shown in lower subplot
    st,en = i/5-0.5, i/5+0.5
    l1.set_data([st,st],[-1,1])
    l2.set_data([en,en],[-1,1])
    ax2.set_xlim(st,en)
    return fig,

# Animate
ani = animation.FuncAnimation(fig, animate, fargs=(l1,l2),
                               frames=NUMFRAMES, interval=100, blit=True)

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

In [3]:
fn = 'animate_xlims_funatnimation'
ani.save(fn+'.mp4',writer='ffmpeg',fps=1000/100)
ani.save(fn+'.gif',writer='imagemagick',fps=1000/100)

Reduce the size of the GIF file using imagemagick.

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

Finaly, show the animation in the jupyter notebook.

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