0
0
Matplotlibdata~5 mins

Time series with fill_between in Matplotlib

Choose your learning style9 modes available
Introduction

We use fill_between to color the area between two lines in a time series plot. This helps to see the range or difference clearly.

To show the range between minimum and maximum values over time.
To highlight the difference between two related time series.
To visualize confidence intervals around a time series line.
To emphasize periods where one value is above or below another.
To make time series plots easier to understand at a glance.
Syntax
Matplotlib
plt.fill_between(x, y1, y2=0, where=None, interpolate=False, color=None, alpha=None, label=None)

x is the time or x-axis values.

y1 and y2 are the two lines between which the area is filled.

Examples
Fill area between values and zero with a light blue color.
Matplotlib
plt.fill_between(dates, values, color='skyblue', alpha=0.5)
Fill area between lower_bound and upper_bound to show a range.
Matplotlib
plt.fill_between(dates, lower_bound, upper_bound, color='lightgreen', alpha=0.3)
Fill area only where series1 is greater than series2.
Matplotlib
plt.fill_between(dates, series1, series2, where=(series1 > series2), color='red', alpha=0.4)
Sample Program

This code plots two time series lines and colors the area between them in light blue. It helps to see the difference between the two series over time.

Matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Create a date range
dates = pd.date_range(start='2024-01-01', periods=10)

# Create two time series
series1 = np.array([10, 12, 15, 14, 13, 16, 18, 17, 19, 20])
series2 = np.array([8, 9, 11, 10, 12, 13, 14, 15, 16, 18])

plt.figure(figsize=(8,4))
plt.plot(dates, series1, label='Series 1', color='blue')
plt.plot(dates, series2, label='Series 2', color='green')

# Fill area between series1 and series2
plt.fill_between(dates, series1, series2, color='lightblue', alpha=0.5)

plt.title('Time Series with fill_between')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

Use alpha to control transparency so the lines remain visible.

The where parameter can highlight specific areas conditionally.

Make sure your x-axis values are sorted for correct filling.

Summary

fill_between colors the area between two lines in a plot.

It makes differences or ranges in time series easy to see.

Use transparency and conditions to customize the fill.