Saving Animations with PillowWriter in Python

The PillowWriter class from matplotlib.animation is a writer that allows us to save animations we create in matplotlib. Pillow is a fork of the Python Image Library (PIL). Both PIL and Pillow come with matplotlib. The matplotlib.animation.PillowWriter class is the image writer class for the matplotlib.animation module.

matplotlib logo
matplotlib logo Image from matplotlib

In this post, we’re going to cover the class signature of matplotlib.animation.PillowWriter, including its parameters, methods, and attributes. Then we’ll go over an example of how to use PillowWriter to save an animation via the animation of a sine wave. It’ll be an extension of the animation example we covered for the post on animation.FuncAnimation.

PillowWriter Class Signature

class matplotlib.animation.PillowWriter(fps=5, metadata=None, codec=None, bitrate=None)

The PillowWriter class has four parameters. None of these parameters are required. The four parameters are fps, metadata, codec, and bitrate. PillowWriter also has five methods (other than __init__), and one attribute. The methods are finish, grab_frame, isAvailable, saving, and setup. PillowWriter’s one attribute is frame_size.

Python PillowWriter Parameters

Let’s take a look at the four PillowWriter parameters. Only fps has a default, the other three default to None.

ParameterTypeDescription
fpsintDefaults to 5, represents frames per second that the animation will be saved at
metadatadict, NoneDefaults to an empty dict. Represents the metadata of the animation.
codecstring, NoneDefaults to the animation.codec default from matplotlib. Represents the video codec to use.
bitrateint, NoneDefaults to the animation.bitrate default from matplotlib. Represents the bitrate to save the animation at.
PillowWriter Parameters

Python PillowWriter Methods

There are five methods in `matplotlib.animation.PillowWriter`. Three of these methods are instance methods, one is a class method, and one is an inherited method.

Instance MethodParametersDescription
setupfig, outfile, dpiSet up saving the animation. fig is the matplotlib.figure.Figure containing the animation, outfile is the name of the file we’re saving to, and dpi is a float representing the resolution of the file and defaults to 100.
grab_framesavefig_kwargsGrab the current image in the Figure and save it. Passes savefig_kwargs the the savefig function of matplotlib.figure.Figure.
finishFinish processes for writing the movie
PillowWriter Methods and Functions

The one class method in `PillowWriter` is `isAvailable`. It represents whether the writer is available, and defaults to returning `True`. The one inherited method for `PillowWriter` is `saving`. `saving` takes up to five arguments, `fig`, `outfile`, dpi`, `args`, and `kwargs`. It’s a context manager that calls the `setup` method of the superclass. It basically does the same thing that the `matplotlib.animation.PillowWriter` `setup` method does.

Python PillowWriter Attributes

The `PillowWriter` class only has one attribute, `frame_size`. This attribute is a `(width, height)` tuple that represents the number of pixels in the width and height of each frame.

Save Animations with PillowWriter

Example Sine Function Animated and Saved with PillowWriter
Example Sine Function Animated and Saved with PillowWriter

All we have to do to save an animation with `PillowWriter` is have an animation to save. In this example, we’re going to do the exact same thing we did in the `FuncAnimation` tutorial except we’re going to show how to save the animation. We’ll build a simple example of an animation of a Sine function, the same function we used for our Recurrent Neural Network example. To follow this example you’ll need to install two libraries, `numpy` for the numerical data to plot and `matplotlib` (obviously) to use `FuncAnimation`, `PillowWriter`, and plot a figure. We can do this with the line below in the terminal.

pip install numpy matplotlib

Python Code for Creating the Animation with FuncAnimation

For a more detailed description of the code for creating this animation, read How to Make Animations with FuncAnimation. Basically what we’re going to do is create the animation that you see at the beginning of this section. We plot a sine wave and then plot multiple points along the wave as a red dot.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
 
fig, ax = plt.subplots()
 
#plot sine function
_range = np.arange(0, 2*np.pi, 0.001)
sine = np.sin(_range)
line = plt.plot(_range, sine)
 
ax = plt.axis([0, 2*np.pi, -1, 1])
dot, = plt.plot([0], [np.sin(0)], 'ro') #plt.plot returns a tuple
 
def func(i):
    dot.set_data(i, np.sin(i))
    return dot, #return the unpacked tuple
   
_animation = FuncAnimation(fig, func, frames=np.arange(0, 2*np.pi, 0.1), interval=10, repeat=True)
plt.show()

Python Code for Saving the Animation with PillowWriter

We only need three lines of code to save an animation. First, we’ll import the `PillowWriter` class from `matplotlib.animation`. Then we’ll create a writer using the `PillowWriter` class, in this example, we’ll give it an fps of 30 instead of 5. Finally, we call the `save` method from the animation and pass in a filename and the writer.

from matplotlib.animation import PillowWriter
writer = PillowWriter(fps=30)
_animation.save("sine_example.gif", writer=writer)

Further Reading

Learn More

To learn more, feel free to reach out to me @yujian_tang on Twitter, connect with me on LinkedIn, and join our Discord. Remember to follow the blog to stay updated with cool Python projects and ways to level up your Software and Python skills! If you liked this article, please Tweet it, share it on LinkedIn, or tell your friends!

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang
Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

One thought on “Saving Animations with PillowWriter in Python

Leave a Reply

%d bloggers like this: