Matplotlib fill_between Animation in Python

I have found that animations can transform static charts into compelling stories. One of the most powerful yet underutilized features in Matplotlib is the fill_between function. It lets you shade the area between two curves, which is perfect for illustrating confidence intervals, ranges, or trends. But when you combine fill_between with animation, the results become truly dynamic and insightful.

In this article, I will walk you through how to create smooth and visually appealing animations using Matplotlib’s fill_between in Python. Whether you’re a data scientist, analyst, or developer, this tutorial will help you add a new dimension to your data visualization toolkit.

What is Matplotlib fill_between Animation?

Matplotlib’s fill_between function fills the area between two horizontal curves on a plot. By animating this fill, you can show how data ranges or confidence intervals, evolve. This is particularly useful in fields like finance, weather forecasting, or any domain where trends and variability matter.

Animating fill_between involves updating the shaded area frame-by-frame, creating a fluid visual effect that communicates changes more effectively than static images.

Method 1: Basic fill_between Animation Using FuncAnimation

The simplest way to animate fill_between in Python is by using Matplotlib’s FuncAnimation. This method updates the shaded area in each frame based on your data.

Here is a complete example that animates a sine wave with a dynamically shaded area between two curves:

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

# Create figure and axis
fig, ax = plt.subplots()
x = np.linspace(0, 4 * np.pi, 200)

# Initial data for sine wave and fill boundaries
y1 = np.sin(x)
y2 = y1 + 0.5

# Plot initial lines and fill
line, = ax.plot(x, y1, color='blue')
fill = ax.fill_between(x, y1, y2, color='skyblue', alpha=0.5)

ax.set_ylim(-2, 2)
ax.set_title('Animated fill_between with sine wave')

def update(frame):
    # Update y-data for dynamic animation
    y1 = np.sin(x + frame / 10)
    y2 = y1 + 0.5 * np.abs(np.cos(frame / 10))

    # Update the line
    line.set_ydata(y1)

    # Remove old fill and draw new fill_between
    ax.collections.clear()
    ax.fill_between(x, y1, y2, color='skyblue', alpha=0.5)

    return line,

# Create animation
ani = FuncAnimation(fig, update, frames=100, interval=50, blit=False)

plt.show()

You can refer to the screenshot below to see the output.

Matplotlib fill_between Animation Python
  • We define two curves, y1 and y2, that change over time.
  • In the update function, we recalculate these curves for each frame.
  • We clear the previous fill and redraw it to reflect the new shaded area.
  • The animation runs smoothly, showing how the shaded region evolves.

Method 2: Advanced fill_between Animation with Blitting for Performance

When working with larger datasets or more complex animations, performance can suffer. Using blitting optimizes the redraw process, updating only parts of the plot that change.

Here’s how you can adapt the previous example with blitting:

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

fig, ax = plt.subplots()
x = np.linspace(0, 4 * np.pi, 200)
y1 = np.sin(x)
y2 = y1 + 0.5

line, = ax.plot(x, y1, color='blue')
fill = ax.fill_between(x, y1, y2, color='skyblue', alpha=0.5)

ax.set_ylim(-2, 2)
ax.set_title('fill_between Animation with Blitting')

def update(frame):
    y1 = np.sin(x + frame / 10)
    y2 = y1 + 0.5 * np.abs(np.cos(frame / 10))

    line.set_ydata(y1)

    # Instead of clearing all, remove previous fill manually
    global fill
    fill.remove()
    fill = ax.fill_between(x, y1, y2, color='skyblue', alpha=0.5)

    return line, fill

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

plt.show()

You can refer to the screenshot below to see the output.

Matplotlib fill_between Animation
  • We remove the old fill area explicitly before drawing a new one.
  • The blit=True argument ensures only the changed parts are redrawn, improving efficiency.
  • This method is ideal when animating large or complex datasets.

Practical Use Case: Visualize Stock Price Ranges in the USA Market

To make this more relatable to a US audience, imagine you want to animate the daily high and low prices of a stock like Apple Inc. over a month. Using the fill_between animation, you can dynamically display the price range as it changes day by day.

Here’s a simplified snippet simulating such data:

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

days = np.arange(1, 31)
np.random.seed(0)
low_prices = np.random.uniform(140, 150, size=30)
high_prices = low_prices + np.random.uniform(1, 5, size=30)

fig, ax = plt.subplots()
ax.set_xlim(1, 30)
ax.set_ylim(135, 160)
ax.set_title('Apple Inc. Daily Price Range - Animated')
ax.set_xlabel('Day of Month')
ax.set_ylabel('Price (USD)')

line_low, = ax.plot(days, low_prices, color='red', label='Low Price')
line_high, = ax.plot(days, high_prices, color='green', label='High Price')
fill = ax.fill_between(days, low_prices, high_prices, color='lightgreen', alpha=0.5)

def update(frame):
    # Shift prices to simulate daily changes
    shift = np.sin(frame / 5) * 2
    new_low = low_prices + shift
    new_high = high_prices + shift

    line_low.set_ydata(new_low)
    line_high.set_ydata(new_high)

    global fill
    fill.remove()
    fill = ax.fill_between(days, new_low, new_high, color='lightgreen', alpha=0.5)

    return line_low, line_high, fill

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

plt.legend()
plt.show()

You can refer to the screenshot below to see the output.

fill_between Animation in Python Matplotlib

This animation helps investors and analysts visually track how the price range fluctuates over time, making it easier to spot trends or anomalies.

Tips for Creating Effective fill_between Animations in Python

  • Keep it simple: Don’t overload your animation with too many moving parts. Focus on the key data you want to highlight.
  • Use transparency: The alpha parameter in fill_between helps keep the plot readable by making fills semi-transparent.
  • Label clearly: Always add titles, axis labels, and legends to orient your audience.
  • Optimize performance: For longer animations or bigger datasets, use blitting and avoid unnecessary redraws.
  • Test different color schemes: Colors can greatly impact how your animation is perceived, so choose palettes that enhance clarity.

Using Matplotlib’s fill_between animation in Python can elevate your data storytelling. Whether you want to show confidence intervals, ranges, or dynamic trends, animating the shaded area between curves adds clarity and engagement.

I encourage you to try these methods with your own datasets. Experiment with different update functions and see how animation can make your Python visualizations stand out.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.