DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

How to Animate Matplotlib fill_between in Python

A working Python pattern for animating a Matplotlib fill_between region, with callback guidance, mask and intersection behavior, and export options.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To animate a shaded region with Matplotlib, create the plot once, then use FuncAnimation to update the curve and its fill on each frame. For a straightforward implementation, remove the previous fill collection and create a new one in the callback. Keep the animation object in a live variable so it is not garbage-collected while the animation runs.

Minimal working example

This example animates a sine curve and the area between it and zero. It uses blit=False to keep the update pattern simple.

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

x = np.linspace(0, 2 * np.pi, 300)
fig, ax = plt.subplots()
ax.set(xlim=(x.min(), x.max()), ylim=(-1.2, 1.2))
ax.set_xlabel("x")
ax.set_ylabel("value")

fill = ax.fill_between(x, 0, 0, alpha=0.35)
line, = ax.plot(x, np.zeros_like(x), color="C0")

def update(frame):
    global fill
    phase = frame * 0.08
    y = np.sin(x + phase)
    line.set_ydata(y)
    fill.remove()
    fill = ax.fill_between(x, 0, y, color="C0", alpha=0.35)
    return line, fill

ani = FuncAnimation(fig, update, frames=100, interval=30, blit=False)
plt.show()

The initial fill and line establish the artists before the animation begins. Each callback computes new data, updates the existing line, removes the old fill collection, and adds a replacement. The global declaration keeps this short example compact; a closure or small state object is a cleaner way to store the current fill in reusable code.

How the update callback works

FuncAnimation calls the update function for each frame. The callback receives the frame value and should return an iterable containing the artists it changed. In this example, that is the line and the newly created fill.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • frames=100 supplies 100 frame values.
  • interval=30 sets the delay between frames in milliseconds; it is not a guarantee of a particular playback rate.
  • blit=False redraws without using blitting, which avoids blitting-specific requirements for this basic example.

Retain ani as a live variable for as long as the animation should run. Matplotlib warns that an unreferenced animation object can be garbage-collected, stopping the animation. See the FuncAnimation API reference.

What fill_between fills

fill_between(x, y1, y2) creates filled polygons between two curves. If you omit y2, it defaults to zero, so ax.fill_between(x, y) shades between the curve and the horizontal axis baseline. You can pass another array as y2 to shade between two changing curves. The fill_between API reference documents these arguments and the options below.

Use where masks for selected spans

The where argument selects which sections to fill, but selection applies to intervals between neighboring x positions. An interval is filled only if both where[i] and where[i + 1] are true. A lone True value surrounded by false values therefore does not create a filled span.

Handle crossings with interpolation

When the boundary curves cross and the selected region is meant to include that crossing, set interpolate=True. Without interpolation, the polygon is formed using the supplied x nodes, which can clip the filled region around an intersection.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Represent step-shaped data

Set step to 'pre', 'post', or 'mid' when the fill should follow a step function. These options determine where the step transitions occur.

Choose a simple redraw or blitting

Removing and recreating the fill each frame is easy to understand and is often adequate for modest frame counts and datasets. If redraw time becomes a problem, investigate updating a persistent collection and measure performance with your actual plot, backend, and output method; not every fill update necessarily benefits equally.

Blitting can reduce redraw work by reusing a saved background and drawing only changed artists. To use it, return every changed artist from the callback and test the result with the backend you intend to use. With blitting, animated artists are drawn above prior artists, although their relative z-order among animated artists is respected. Consult the Matplotlib animation API overview for details.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Save or embed the animation

Matplotlib offers file output through Animation.save and HTML output through to_html5_video or to_jshtml. Available writer families include Pillow for GIF, FFmpeg for video, ImageMagick for GIF, and an HTML writer. External writers may require software installed in the environment that creates the animation, so check writer availability there. The documentation does not name one best writer for every platform or destination.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • For a standalone file, use ani.save(...) with a writer supported by the generating environment.
  • For an HTML5 video representation, use ani.to_html5_video().
  • For a JavaScript-based HTML representation, use ani.to_jshtml().

For example, a GIF export using Pillow can be written as ani.save("animation.gif", writer="pillow") if Pillow is installed and available to Matplotlib. See the animation API overview and writer documentation for output methods and writer options.

Account for transparency

If your fill uses alpha transparency, choose and verify the output format and playback target. Matplotlib’s fill_between transparency example notes that PostScript does not support alpha and recommends GIF, PNG, PDF, or SVG for figures using alpha. That guidance concerns figure formats; it does not establish transparency behavior for every animation writer.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.