Matplotlib's animations when displayed inline by using %matplotlib notebook are very choppy and cannot be paused although they have the advantage of being displayed straight away. If a smooth animation is wanted along with the ability to pause then the PyCav module display can be used. This notebook will demonstrates its use, the documentation can also been found in the PyCav library documentation.
As an example we shall animate a moving sin wave. We create a numpy array containing the data we require to produce the animation. Creating a figure and a function which steps through the time slices of the plot, we call the matplotlib FuncAnimation function, passing it the figure, the next frame function and the number of frames in the animation.
#NAME: Inline Animation Tutorial #DESCRIPTION: How to use Matplotlib Animations and PyCav.display for inline notebook animation # Use these two lines on environments without displays i.e. servers #import matplotlib #matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.animation as anim import pycav.display as display import numpy as np x = np.linspace(0.,10.,101) t = np.linspace(0.,10.,51) sin_x = np.zeros((101,51)) for i in range(51): sin_x[:,i] = np.sin(np.pi*x-np.pi*t[i]) fig = plt.figure(figsize = (7,7)) ax = plt.subplot(111) line = ax.plot(x,sin_x[:,0]) def nextframe(arg): line.set_data(x,sin_x[:,arg+1]) animate1 = anim.FuncAnimation(fig,nextframe,interval = 100,frames = 50, repeat = False)
Suppose we are creating an animation which we do not want store in memory. We can use the temp = True argument to write the animation to a temporary file. The information about the produced video is appended to the animate object so we must pass this and set it as the output as well.
animate1 = display.create_animation(animate1,temp = True)
Now we can call the display_animation function which takes this animate object as the argument and displays the created video.
Suppose now we wish to create a permanant file in the directory of the notebook you are working in. Now we must give create_animation the filename as a string. Now display_animation can be passed the file name as an argument and it will display it.
animate1 = display.create_animation(animate1,fname = 'example.mp4') display.display_animation(animate1)
You will notice if you run the above cell twice it takes the same amount of time each time. This is because the file 'example.mp4' is being overwritten. If this is not desired then overwrite can be set to False. Then only if the filename does not exist will a new file will be created.
The code below if run will not overwrite the example file so will very quickly display the example.mp4 animation
animate1 = display.create_animation(animate1,fname = 'example.mp4', overwrite = False) display.display_animation('example.mp4')