# Matplotlib fill_between: Shade Between Lines, Under a Curve, and Around a Band

> ax.fill_between(x, y1, y2) shades the area between two curves in Matplotlib. Examples for filling under a line, where= and interpolate=, confidence bands, full-height regions, fill_betweenx, and step fills.

Source: https://www.pythoncharts.com/matplotlib/matplotlib-fill-between/ | Published: 2026-12-05 | Author: Alex Scott | Category: Matplotlib | Tags: matplotlib, fill_between, shading, line plot, confidence interval

`ax.fill_between(x, y1, y2)` shades the area between two curves in Matplotlib. Leave out `y2` and it fills down to zero; pass a single number and it fills to that level. `where=` limits the shading to the x values where a condition is true. `plt.fill_between()` takes the same arguments if you use the pyplot interface.

## Quick Example

This shades the daily low-to-high temperature range for a year and draws the seasonal normal on top.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

rng = np.random.default_rng(23)
days = pd.date_range("2025-01-01", periods=365, freq="D")
doy = np.arange(365)
normal = 56 - 22 * np.cos(2 * np.pi * (doy - 15) / 365)
weather = np.convolve(rng.normal(0, 7, 371), np.ones(7) / 7, mode="valid")
mean_temp = normal + weather
high = mean_temp + 9 + rng.normal(0, 2, 365)
low = mean_temp - 9 + rng.normal(0, 2, 365)

fig, ax = plt.subplots(figsize=(9, 4.5), layout="constrained")
ax.fill_between(days, low, high, color="#f4a261", alpha=0.45, linewidth=0,
                label="Daily low to high")
ax.plot(days, normal, color="#264653", linestyle="--", label="Seasonal normal")
ax.set_ylabel("Temperature (°F)")
ax.legend(loc="upper left")
plt.show()
```

![A year of daily temperatures drawn as an orange band from each day's low to its high, with a dashed seasonal normal line running through the middle](https://www.pythoncharts.com/matplotlib/matplotlib-fill-between/images/fill-between-quick-example.png)

`fill_between` returns a filled shape, not a line, so `label=` gives it its own legend entry. `linewidth=0` removes the thin outline Matplotlib draws around the fill by default.

## `fill_between` parameters

| Parameter | What it does |
|---|---|
| `x` | The x values. Numbers, dates, and pandas Series all work |
| `y1` | The first curve |
| `y2=0` | The second curve: an array, or a scalar for a flat baseline |
| `where=` | Boolean array. Only fill where it's `True` |
| `interpolate=False` | With `where=`, extend each fill to the exact point where the curves cross |
| `step=None` | `"pre"`, `"post"`, or `"mid"` to fill as a step function |
| `color`, `alpha`, `hatch`, `edgecolor`, `linewidth`, `label`, `zorder` | Styling, passed through to the filled shape |

## How do I fill under a curve?

Pass only `x` and `y1`. `y2` defaults to 0, so the fill runs from the line down to zero.

```python
hours = np.linspace(5, 20, 200)
solar_kw = np.clip(6.5 * np.sin(np.pi * (hours - 5.5) / 14), 0, None)

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.plot(hours, solar_kw, color="#e9c46a", linewidth=2)
ax.fill_between(hours, solar_kw, color="#e9c46a", alpha=0.35)
ax.set_ylim(bottom=0)
ax.set_xlabel("Hour of day")
ax.set_ylabel("Solar output (kW)")
plt.show()
```

![A yellow line of solar output rising from zero at dawn to a midday peak near 6.5 kW and back to zero, with the area under it shaded](https://www.pythoncharts.com/matplotlib/matplotlib-fill-between/images/fill-between-under-curve.png)

The area under this curve is the day's energy, which `np.trapezoid(solar_kw, hours)` puts at about 58 kWh. For a baseline other than zero, pass it as `y2`, for example `ax.fill_between(x, y, 50)`.

## Shade only where a condition is true (`where=` and `interpolate=`)

`where=` takes a boolean array the same length as `x`. A common use is to color the gap between two lines differently depending on which one is higher. Here the gap between the daily mean and the normal is red on warm days and blue on cool ones. The two panels show the same 30 days with and without `interpolate=True`.

```python
import matplotlib.dates as mdates

window = slice(60, 90)
d, t, n = days[window], mean_temp[window], normal[window]

fig, axs = plt.subplots(1, 2, figsize=(10, 4), sharey=True, layout="constrained")
for ax, interp in zip(axs, [False, True]):
    ax.plot(d, t, color="black", linewidth=1.2)
    ax.plot(d, n, color="gray", linestyle="--")
    ax.fill_between(d, t, n, where=t >= n, interpolate=interp,
                    color="#e63946", alpha=0.5, label="Warmer than normal")
    ax.fill_between(d, t, n, where=t < n, interpolate=interp,
                    color="#457b9d", alpha=0.5, label="Cooler than normal")
    ax.set_title(f"interpolate={interp}")
    ax.xaxis.set_major_locator(mdates.DayLocator(bymonthday=[1, 8, 15, 22]))
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %d"))
axs[0].legend(loc="upper left")
plt.show()
```

![Two panels of 30 days of temperature against the normal; red fills where it is warmer and blue where cooler. With interpolate=False there are white wedges where the lines cross; with interpolate=True the fills meet exactly at the crossings](https://www.pythoncharts.com/matplotlib/matplotlib-fill-between/images/fill-between-where-interpolate.png)

Without `interpolate`, each fill stops at the last x value where the condition was true, which leaves white wedges at every crossing. With `interpolate=True` both fills run to the exact crossing point. Turn it on whenever `where=` compares two curves.

## How do I plot a confidence band or forecast interval?

Compute the lower and upper bounds, then fill between them. Layering a wide, light band under a narrower, darker one makes a fan chart:

```python
weeks = np.arange(1, 41)
history = 120 + 1.5 * weeks[:28] + rng.normal(0, 6, 28)
ahead = np.arange(1, 13)
forecast = history[-1] + 1.5 * ahead
sd = 6 * np.sqrt(ahead)
future = weeks[28:]

fig, ax = plt.subplots(figsize=(9, 4.5), layout="constrained")
ax.plot(weeks[:28], history, color="#2a9d8f", marker="o", markersize=3, label="Actual")
ax.fill_between(future, forecast - 1.645 * sd, forecast + 1.645 * sd,
                color="#2a9d8f", alpha=0.18, linewidth=0, label="90% interval")
ax.fill_between(future, forecast - 0.674 * sd, forecast + 0.674 * sd,
                color="#2a9d8f", alpha=0.35, linewidth=0, label="50% interval")
ax.plot(future, forecast, color="#2a9d8f", linestyle="--", label="Forecast")
ax.set_xlabel("Week")
ax.set_ylabel("Orders")
ax.legend(loc="upper left")
plt.show()
```

![Weekly orders for 28 weeks followed by a dashed 12-week forecast with a dark 50% interval band inside a lighter 90% band that widens further into the future](https://www.pythoncharts.com/matplotlib/matplotlib-fill-between/images/fill-between-forecast-band.png)

1.645 and 0.674 are the normal quantiles for 90% and 50% intervals. The bands widen with `np.sqrt(ahead)` because forecast error grows the further out you go. For a band computed from data, Seaborn's `lineplot` draws one automatically; see [confidence interval bands in Seaborn](https://www.pythoncharts.com/seaborn/seaborn-confidence-interval-bands/).

## Shade full-height regions from a boolean mask

To shade every period that meets a condition (every heat wave, every weekend, every recession) in one call, fill from 0 to 1 using `ax.get_xaxis_transform()`. That transform reads x as data values and y as a fraction of the axes height, so the shading always covers the whole plot height:

```python
hot = high >= 85

fig, ax = plt.subplots(figsize=(9, 4.5), layout="constrained")
ax.plot(days, high, color="#bc4749", linewidth=1)
ax.fill_between(days, 0, 1, where=hot, transform=ax.get_xaxis_transform(),
                color="#bc4749", alpha=0.15, linewidth=0, label="High of 85°F or more")
ax.axhline(85, color="#bc4749", linestyle=":", linewidth=1)
ax.set_ylabel("Daily high (°F)")
ax.legend(loc="upper left")
plt.show()
```

![A year of daily highs with light red vertical bands covering the full plot height on every summer day whose high reached 85°F](https://www.pythoncharts.com/matplotlib/matplotlib-fill-between/images/fill-between-full-height.png)

In this data that's 54 days, from June to September and mostly in July and August, all shaded with one call. For one known date range, `ax.axvspan(start, end)` is simpler; see [highlighting a date range](https://www.pythoncharts.com/matplotlib/matplotlib-highlight-date-range-area/).

## `fill_betweenx`: fill between two vertical curves

When the curves are functions of y, such as a profile against depth or altitude, use `ax.fill_betweenx(y, x1, x2)`. It's the same function with the axes swapped.

```python
depth = np.linspace(0, 400, 120)
winter = 4 + 8 * np.exp(-depth / 120)
summer = winter + 12 * np.exp(-depth / 40)

fig, ax = plt.subplots(figsize=(5, 6), layout="constrained")
ax.fill_betweenx(depth, winter, summer, color="#48cae4", alpha=0.4,
                 label="Seasonal range")
ax.plot(winter, depth, color="#023e8a", label="Winter")
ax.plot(summer, depth, color="#f77f00", label="Summer")
ax.invert_yaxis()
ax.set_xlabel("Water temperature (°C)")
ax.set_ylabel("Depth (m)")
ax.legend(loc="lower right")
plt.show()
```

![Water temperature against depth with depth increasing downward; the winter and summer profiles meet near 4°C at depth and the shaded seasonal range is widest at the surface, from 12 to 24°C, and narrows to nothing by 400 m](https://www.pythoncharts.com/matplotlib/matplotlib-fill-between/images/fill-betweenx-depth-profile.png)

[`invert_yaxis()`](https://www.pythoncharts.com/matplotlib/matplotlib-invert-axis-direction/) puts the surface at the top. The seasonal range is 12°C at the surface, under 1°C below 100 m, and close to zero by 400 m.

## Step fills with `step=`

If the data is a step function, such as prices that hold until the next change, fill with `step=` and draw the line with `ax.step()`. Use the same value in both (`"post"` here) or the fill and the line won't line up.

```python
hour = np.arange(0, 25)
rate = np.select([hour < 7, hour < 16, hour < 21], [0.11, 0.18, 0.36], 0.11)

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.step(hour, rate, where="post", color="#6a4c93", linewidth=2)
ax.fill_between(hour, rate, step="post", color="#6a4c93", alpha=0.25)
ax.set_xticks(range(0, 25, 3))
ax.set_xlim(0, 24)
ax.set_ylim(bottom=0)
ax.set_xlabel("Hour of day")
ax.set_ylabel("Electricity rate ($/kWh)")
plt.show()
```

![A purple step chart of an electricity rate that is 0.11 dollars overnight, 0.18 from 7am, 0.36 at peak from 4pm to 9pm, then back to 0.11, with the area under the steps shaded](https://www.pythoncharts.com/matplotlib/matplotlib-fill-between/images/fill-between-step.png)

Without `step=`, the fill would slope diagonally from one rate to the next and wouldn't match the line. The [step and stem plot post](https://www.pythoncharts.com/matplotlib/matplotlib-step-stem-plots/) explains `"pre"`, `"post"`, and `"mid"`.

## `fill_between` vs `axvspan` vs `stackplot`

| Goal | Use |
|---|---|
| Shade between two curves or under one curve | `ax.fill_between(x, y1, y2)` |
| Shade one known x range or y range | `ax.axvspan(x0, x1)` or `ax.axhspan(y0, y1)` |
| Shade many x ranges from a condition | `fill_between(x, 0, 1, where=mask, transform=ax.get_xaxis_transform())` |
| Stack several series on top of each other | `ax.stackplot(x, ys)`; see [area charts](https://www.pythoncharts.com/matplotlib/matplotlib-area-chart/) |
| Fade the fill from the line to the axis | An image clipped to the fill; see [gradient fills](https://www.pythoncharts.com/matplotlib/matplotlib-gradient-fill-under-line/) |
| Curves that are functions of y | `ax.fill_betweenx(y, x1, x2)` |

## Practical Tips

- **Draw order:** fills are drawn below lines by default. If a fill hides a grid or another fill, set `zorder` or lower `alpha`.
- **Missing values:** `NaN` in `y1` or `y2` breaks the fill into separate pieces instead of bridging the gap, the same as a line does.
- **Hatching:** `hatch="//"` with `facecolor="none"` and an `edgecolor` gives a patterned fill that survives grayscale printing. See [hatch patterns](https://www.pythoncharts.com/matplotlib/matplotlib-hatch-patterns/).
- **Animating a fill:** since Matplotlib 3.10, `fill_between` returns a `FillBetweenPolyCollection` with a `set_data(x, y1, y2)` method, so you can update the shape instead of removing and redrawing it.

## Similar Topics

- [Area Charts and Stacked Area Charts in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-area-chart/)
- [Add Gradient Fills Under a Line Plot in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-gradient-fill-under-line/)
- [Highlight a Specific Date Range or Area in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-highlight-date-range-area/)
