Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Exporting Animations in Matplotlib

Learn how to save Matplotlib animations as GIF, MP4, and other supported formats using animation writers.

Understand Pillow, FFmpeg, FPS, DPI, bitrate, output quality, and how to export animations for presentations and applications.

1. Learning Objectives

After completing this lesson, you will understand:

  • What animation exporting means.
  • How to save animations using the save() method.
  • How to export animations as GIF files.
  • How to export animations as MP4 videos.
  • How Pillow and FFmpeg writers work.
  • How to configure frames per second.
  • How to control output resolution using DPI.
  • How to configure video bitrate.
  • How to check available animation writers.
  • How to troubleshoot common exporting errors.

2. What Is Animation Exporting?

Animation exporting is the process of saving an animated visualization into a file that can be viewed or shared outside the Python application.

Matplotlib provides the save() method for exporting animations. Depending on the selected writer and installed dependencies, animations can be saved in formats such as GIF and MP4.

Why Export Animations?

  • To share animated graphs with other people.
  • To include animations in presentations.
  • To create educational demonstration videos.
  • To save scientific simulation results.
  • To use animations in reports and documentation.
  • To store visualization results for future reference.

3. Animation Exporting Workflow

Exporting an animation involves creating the figure, defining animation frames, selecting a suitable writer, and saving the resulting file.

Create Animation Select Animation Writer Configure Export Settings Save Animation File

Basic workflow for exporting a Matplotlib animation.

4. Using the save() Method

Matplotlib animation objects provide the save() method. It exports the animation using the selected writer and configuration options.

Basic Syntax

ani.save(
    filename,
    writer=None,
    fps=None,
    dpi=None,
    bitrate=None
)

Important Parameters

Parameter Description
filename Name or path of the output animation file.
writer Animation writer used to create the output file.
fps Frames per second in the exported animation.
dpi Resolution setting used when rendering animation frames.
bitrate Video bitrate setting, primarily relevant to video writers.

Example

ani.save(
    "output_animation.gif",
    writer="pillow",
    fps=20
)

Output

Animation saved successfully.

Output file:
output_animation.gif

The example assumes that the animation object already exists and the required Pillow dependency is installed.

5. Understanding Animation Writers

Animation writers are responsible for encoding the rendered animation frames into a final file format.

Matplotlib provides different writer implementations for different output formats.

Writer Typical Output Requirement
PillowWriter GIF Pillow Python package.
FFMpegWriter MP4 and supported video formats. FFmpeg executable.
ImageMagickWriter Animated image formats supported by ImageMagick. ImageMagick installation.
HTMLWriter HTML animation output. Matplotlib HTML writer support.
Tip: Choose the writer according to the required output format and the dependencies available on your computer.

6. Exporting Animation as GIF Using Pillow

Pillow is a Python imaging library that can be used by Matplotlib to create animated GIF files.

Step 1: Install Pillow

pip install pillow

Step 2: Import Required Libraries

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
import numpy as np

Step 3: Create and Save an Animation

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
import numpy as np

fig, ax = plt.subplots()

x = np.linspace(0, 2 * np.pi, 100)

line, = ax.plot([], [], "b-")

ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1.5, 1.5)

def update(frame):

    y = np.sin(x + frame * 0.1)

    line.set_data(x, y)

    return line,

ani = FuncAnimation(
    fig,
    update,
    frames=50,
    interval=50,
    blit=True
)

ani.save(
    "sine_wave.gif",
    writer=PillowWriter(fps=20)
)

plt.close(fig)

print("GIF exported successfully")

Output

GIF exported successfully

Generated file:
sine_wave.gif
Remember: The GIF file is saved in the current working directory unless you provide a different output path.

7. Exporting Animation as MP4 Using FFmpeg

FFmpeg is a multimedia framework that can encode video files. Matplotlib uses its FFmpeg writer to export animations into supported video formats such as MP4.

Step 1: Install FFmpeg

Install FFmpeg for your operating system and ensure that the FFmpeg executable is available through your system PATH.

Step 2: Import the Required Libraries

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, FFMpegWriter
import numpy as np

Step 3: Create and Export MP4

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, FFMpegWriter
import numpy as np

fig, ax = plt.subplots()

x = np.linspace(0, 2 * np.pi, 100)

line, = ax.plot([], [], "r-", linewidth=2)

ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1.5, 1.5)

def update(frame):

    y = np.sin(x + frame * 0.1)

    line.set_data(x, y)

    return line,

ani = FuncAnimation(
    fig,
    update,
    frames=100,
    interval=50,
    blit=True
)

writer = FFMpegWriter(
    fps=20,
    bitrate=1800
)

ani.save(
    "sine_wave.mp4",
    writer=writer,
    dpi=120
)

plt.close(fig)

print("MP4 exported successfully")

Output

MP4 exported successfully

Generated file:
sine_wave.mp4
Important: Installing a Python package alone does not install the FFmpeg executable. FFmpeg must be installed separately and accessible to Matplotlib.

8. Understanding FPS

FPS means Frames Per Second. It specifies how many frames are displayed in one second of the exported animation.

For example, an animation exported with 20 FPS displays 20 frames per second.

FPS General Playback Behaviour
10 Lower frame rate and less smooth movement.
20 Moderate frame rate.
30 Common video frame rate.
60 Higher frame rate and smoother movement when supported.

Example

ani.save(
    "animation.gif",
    writer="pillow",
    fps=30
)

Output

Animation export configuration:

Frames per second: 30
Output format: GIF
Output file: animation.gif
Tip: The animation's exported playback duration depends on the number of frames and the selected FPS.

9. Controlling Resolution Using DPI

DPI means Dots Per Inch. In Matplotlib, DPI controls the rendering resolution of the figure when animation frames are exported.

A higher DPI generally produces larger, more detailed frames and can increase the output file size and rendering time.

Example

ani.save(
    "high_resolution.gif",
    writer="pillow",
    fps=20,
    dpi=150
)

Output

Animation exported with:

Format: GIF
FPS: 20
DPI: 150
File: high_resolution.gif
DPI Typical Use
72 Lower-resolution screen output.
100 General-purpose output.
150 Higher-resolution output.
300 High-resolution rendering for detailed output.

10. Understanding Video Bitrate

Bitrate represents the amount of data used per second when encoding a video. It can affect the output video quality and file size.

The bitrate parameter is primarily relevant to video writers such as FFmpegWriter.

Example

from matplotlib.animation import FFMpegWriter

writer = FFMpegWriter(
    fps=30,
    bitrate=2000
)

ani.save(
    "output.mp4",
    writer=writer
)

Output

Video export configuration:

FPS: 30
Bitrate: 2000 kbps
Format: MP4
Output file: output.mp4
Note: Bitrate behaviour depends on the video encoder and its configuration. A higher bitrate may increase file size without guaranteeing a proportional improvement in quality.

11. Checking Available Animation Writers

Matplotlib provides a registry that can be used to check whether a particular animation writer is available.

Example

import matplotlib.animation as animation

print("Pillow available:",
      animation.writers.is_available("pillow"))

print("FFmpeg available:",
      animation.writers.is_available("ffmpeg"))

print("ImageMagick available:",
      animation.writers.is_available("imagemagick"))

Output

Pillow available: True
FFmpeg available: True
ImageMagick available: False

These values are example results. Actual availability depends on which packages and external executables are installed and correctly configured on your computer.

Tip: Run this check before exporting an animation to identify missing writer dependencies.

12. Saving Animation to a Custom Folder

You can provide a complete file path to save an animation in a specific directory.

Example

import os

output_folder = "animations"

os.makedirs(output_folder, exist_ok=True)

output_path = os.path.join(
    output_folder,
    "my_animation.gif"
)

ani.save(
    output_path,
    writer="pillow",
    fps=20
)

print("Saved at:", output_path)

Output

Saved at: animations/my_animation.gif

The output folder is created if it does not already exist. The animation file is then saved inside that folder.

13. Comparing Animation Export Formats

Format Writer Common Use
GIF Pillow Short animations and demonstrations.
MP4 FFmpeg Presentations, video sharing, and tutorials.
HTML HTMLWriter Supported HTML-based animation output.
Other video formats Compatible video writer Depends on the installed encoder and format support.

Choosing the Right Format

Use GIF when you need a simple animated image. Use MP4 when you need a video file with configurable frame rate and video encoding. Choose other formats according to the target application and available writer support.

14. Complete Example: Exporting a Sine Wave Animation

This example creates a sine wave animation and exports it as both GIF and MP4 files. It checks writer availability before attempting each export.

Complete Python Code

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()

x = np.linspace(0, 2 * np.pi, 200)

line, = ax.plot([], [], "b-", linewidth=2)

ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1.5, 1.5)

ax.set_title("Exported Sine Wave Animation")
ax.set_xlabel("X Values")
ax.set_ylabel("Sine Values")

def init():
    line.set_data([], [])
    return line,

def update(frame):
    y = np.sin(x + frame * 0.1)
    line.set_data(x, y)
    return line,

ani = FuncAnimation(
    fig,
    update,
    frames=100,
    init_func=init,
    interval=50,
    blit=True
)

if animation.writers.is_available("pillow"):

    ani.save(
        "sine_wave.gif",
        writer="pillow",
        fps=20,
        dpi=100
    )

    print("GIF exported successfully")

else:
    print("Pillow writer is not available")

if animation.writers.is_available("ffmpeg"):

    ani.save(
        "sine_wave.mp4",
        writer="ffmpeg",
        fps=30,
        dpi=100
    )

    print("MP4 exported successfully")

else:
    print("FFmpeg writer is not available")

plt.close(fig)

Output

GIF exported successfully
MP4 exported successfully

Generated files:

sine_wave.gif
sine_wave.mp4

The output shown assumes that both Pillow and FFmpeg writers are available. If either dependency is missing, the corresponding export is skipped.

15. Common Exporting Errors and Solutions

Error or Problem Solution
Pillow writer is unavailable. Install Pillow using pip install pillow.
FFmpeg executable is not found. Install FFmpeg and add its executable location to the system PATH.
Animation file is not generated. Check the output path, file permissions, and writer configuration.
Output video quality is low. Review the DPI, bitrate, and encoder settings.
Exporting takes too much time. Reduce unnecessary frames or rendering complexity.
Output file is too large. Review the resolution, frame count, FPS, and encoding settings.
Animation does not contain expected frames. Check the frames sequence and update function.

16. Best Practices

  • Choose the correct writer for the required output format.
  • Check writer availability before starting the export.
  • Keep a reference to the animation object until exporting finishes.
  • Use an appropriate FPS for the intended playback speed.
  • Choose DPI according to the output resolution requirements.
  • Use a suitable video bitrate when exporting video.
  • Save files in a clearly organized output directory.
  • Test exported files using a compatible media player.
  • Close figures after exporting when they are no longer needed.
  • Handle missing dependencies and file errors appropriately.

17. Practical Activity

Task: Export a Moving Point Animation

Create a Matplotlib animation in which a point moves across a graph and export it as a GIF file.

Requirements:

  1. Import Matplotlib and FuncAnimation.
  2. Create a figure and axes.
  3. Create a moving point.
  4. Write an initialization function.
  5. Write an update function.
  6. Configure 50 animation frames.
  7. Set FPS to 20.
  8. Use the Pillow writer.
  9. Save the animation as moving_point.gif.
  10. Verify the generated file.

Expected Result:

A GIF file should be generated containing a moving point animation that can be opened in a compatible image viewer or browser.

18. Practice Questions

  1. What is animation exporting in Matplotlib?
  2. Which method is used to save an animation?
  3. What is the purpose of an animation writer?
  4. Which writer is commonly used for GIF files?
  5. Which external tool is commonly used for MP4 export?
  6. What does FPS mean?
  7. What is the purpose of DPI?
  8. What does bitrate control in video encoding?
  9. How can you check whether FFmpeg is available?
  10. What is the difference between GIF and MP4 output?
  11. Why might an exported animation have a large file size?
  12. What should you check when an animation export fails?

Summary

Matplotlib supports exporting animations into files using the save() method. Animation writers encode the rendered frames into formats such as GIF and MP4.

PillowWriter is commonly used for GIF export, while FFMpegWriter is used for video export. These writers require their respective dependencies to be installed and available.

Parameters such as FPS, DPI, and bitrate help configure playback speed, rendering resolution, and video encoding. The correct settings depend on the intended output and application requirements.

Checking writer availability, managing output paths, and handling dependencies are important parts of a reliable animation exporting workflow.