Fill Between & Area Plots
Filling the area under or between lines emphasises quantities, ranges and differences. Matplotlib provides fill_between (and its horizontal twin fill_betweenx) for bands and areas, and stackplot for stacked area charts.
Area under a curve
ax.fill_between(x, y) fills from the curve down to y = 0:
import numpy as np
import matplotlib.pyplot as plt
hour = np.arange(0, 25)
solar_kw = np.clip(5 * np.sin((hour - 6) / 12 * np.pi), 0, None)
fig, ax = plt.subplots()
ax.plot(hour, solar_kw, color="orange")
ax.fill_between(hour, solar_kw, color="orange", alpha=0.3)
ax.set(xlabel="Hour", ylabel="Power (kW)", title="Solar panel output", xlim=(0, 24))
plt.show()
energy = np.trapezoid(solar_kw, hour) # area under the curve
print(f"Energy produced: {energy:.1f} kWh")Energy produced: 38.0 kWh
The filled area is the energy, which np.trapezoid computes numerically. Filling makes that quantity visible.
Between two curves
Pass two y arrays to fill the band between them, for example a daily minimum and maximum:
import numpy as np
import matplotlib.pyplot as plt
day = np.arange(1, 32)
rng = np.random.default_rng(6)
low = 8 + 4 * np.sin(day / 31 * np.pi) + rng.normal(0, 1, day.size)
high = low + 7 + rng.normal(0, 1.2, day.size)
fig, ax = plt.subplots(figsize=(7, 4))
ax.fill_between(day, low, high, color="C0", alpha=0.3, label="daily range")
ax.plot(day, (low + high) / 2, color="C0", label="midpoint")
ax.set(xlabel="Day of month", ylabel="°C")
ax.legend()
plt.show()
print(f"Widest range: {(high - low).max():.1f} °C on day {day[(high - low).argmax()]}")Widest range: 9.4 °C on day 11
Conditional fills with where
The where argument fills only where a condition holds. Combined with interpolate=True, the fill stops exactly where the curves cross. This is the classic way to show surpluses and deficits:
import numpy as np
import matplotlib.pyplot as plt
month = np.arange(1, 13)
income = np.array([3200, 3200, 3400, 3400, 3400, 3600, 3600, 3600, 3800, 3800, 3800, 4600])
spend = np.array([3500, 2900, 3100, 3600, 3300, 3200, 4200, 3900, 3300, 3500, 3700, 4900])
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(month, income, color="k", label="Income")
ax.plot(month, spend, color="0.5", linestyle="--", label="Spending")
ax.fill_between(month, income, spend, where=income >= spend, interpolate=True,
color="green", alpha=0.3, label="Saved")
ax.fill_between(month, income, spend, where=income < spend, interpolate=True,
color="red", alpha=0.3, label="Overspent")
ax.set_xticks(month)
ax.legend(ncols=2, loc="upper left")
plt.show()
balance = (income - spend).sum()
print("Months overspent:", int((income < spend).sum()), "| net balance:", balance)Months overspent: 5 | net balance: 300
Stacked area charts
stackplot stacks several series on top of each other, showing both the total and the contribution of each part over time:
import numpy as np
import matplotlib.pyplot as plt
years = np.arange(2015, 2025)
mobile = np.array([20, 26, 33, 40, 47, 54, 60, 64, 68, 71])
desktop = np.array([70, 66, 60, 54, 48, 42, 37, 33, 29, 26])
tablet = np.array([10, 8, 7, 6, 5, 4, 3, 3, 3, 3])
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
ax.stackplot(years, mobile, desktop, tablet, labels=["Mobile", "Desktop", "Tablet"], alpha=0.85)
ax.set(ylabel="Share of visits (%)", ylim=(0, 100), xlim=(2015, 2024))
ax.legend(loc="upper left", bbox_to_anchor=(1.01, 1))
plt.show()
print("Totals per year:", (mobile + desktop + tablet).tolist())Totals per year: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
Here every year adds up to 100 %, so the chart shows how the mix shifted from desktop to mobile.
Horizontal fills
fill_betweenx(y, x1, x2) fills between two x values along y, and axvspan/axhspan shade whole bands across the Axes:
import numpy as np
import matplotlib.pyplot as plt
depth = np.linspace(0, 100, 100)
temp = 4 + 16 * np.exp(-depth / 25)
fig, ax = plt.subplots(figsize=(4, 5), layout="constrained")
ax.plot(temp, depth, color="C0")
ax.fill_betweenx(depth, 4, temp, color="C0", alpha=0.2)
ax.axhspan(20, 40, color="0.85", label="thermocline")
ax.invert_yaxis() # depth increases downwards
ax.set(xlabel="Temperature (°C)", ylabel="Depth (m)")
ax.legend(loc="lower right")
plt.show()
print("y axis inverted:", ax.yaxis_inverted())y axis inverted: True
| Function | Fills |
|---|---|
fill_between(x, y1, y2=0) |
vertically between two curves |
fill_betweenx(y, x1, x2=0) |
horizontally between two curves |
stackplot(x, *ys) |
stacked areas |
fill(x, y) |
an arbitrary closed polygon |
axvspan(x1, x2) / axhspan(y1, y2) |
a full-height or full-width band |
Test yourself
What does ax.fill_between(x, y) fill when only one y array is given?
- Nothing
- Between the curve and y = 0
- Between the curve and the top of the Axes
- Between y and its mean
Why add interpolate=True together with where=?
- To smooth the curves
- So the fill ends exactly where the curves cross
- To make the fill transparent
- It is required for any fill
Which function draws a stacked area chart?
- plt.area()
- plt.stackplot()
- plt.bar(stacked=True)
- plt.fill_stack()