Matplotlib fill_between() / fill_betweenx() Function


Matplotlib 参考文档Matplotlib Reference Documentation

fill_between()Used to fill the region between two horizontal curves,fill_betweenx()Fills the region between two vertical curves.

Often used to visualize confidence intervals, uncertainty ranges, difference areas, etc.

Function Definition

matplotlib.pyplot.fill_between(x, y1, y2=0, where=None,
    interpolate=False, step=None, **kwargs)
matplotlib.pyplot.fill_betweenx(y, x1, x2=0, where=None,
    interpolate=False, step=None, **kwargs)

Parameter Description

ParameterTypeDescription
x / yarrayData points of the first coordinate axis
y1, y2 / x1, x2array or scalarTwo curves. A scalar represents a constant line. y2 defaults to 0, filling to the x-axis.
wherearray of boolSpecifies which intervals need to be filled. True fills, False does not fill.
interpolateboolIf True, interpolate to compute precise boundaries at curve intersections.
stepstrStep fill: 'pre', 'post', 'mid'
color / facecolorcolorFill color
alphafloatTransparency
labelstrLegend label
hatchstrFill patterns: '/'、'\'、'|'、'-'、'+'、'x'、'*'

fill_between and fill_betweenx return aPolyCollectionobject, which can be used for subsequent modification or passed to colorbar.


Usage Examples

Example 1: Fill to the x-axis (default y2=0)

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots(layout='constrained')

# Plot the main curve
ax.plot(x, y, 'b-', linewidth=2, label='sin(x)')
# Fill the area between the curve and the x-axis
ax.fill_between(x, y, alpha=0.3, color='blue',
                label='Area under curve')

ax.set_title('fill_between: Area Between Curve and X-axis')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

Example 2: Confidence interval (area between two curves)

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y_mean = np.sin(x) + 5                     # Mean line
y_std = 0.3 + 0.1 * x                      # Standard deviation increases with x

# Upper and lower bounds
y_upper = y_mean + y_std
y_lower = y_mean - y_std

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')

# Fill the confidence interval on both sides of the mean
ax.fill_between(x, y_lower, y_upper,
                alpha=0.3, color='steelblue',
                label='Confidence Interval')
# Plot the mean line
ax.plot(x, y_mean, 'steelblue', linewidth=2, label='Mean')
# Plot the upper and lower bounds
ax.plot(x, y_upper, 'steelblue', linewidth=0.5, alpha=0.5)
ax.plot(x, y_lower, 'steelblue', linewidth=0.5, alpha=0.5)

ax.set_title('Confidence Interval (fill_between)')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

Example 3: Conditional fill with the where parameter

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 200)
y1 = np.sin(x)
y2 = np.cos(x)

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')

ax.plot(x, y1, 'blue', label='sin(x)')
ax.plot(x, y2, 'red', label='cos(x)')

# Only fill where sin(x) >= cos(x)
ax.fill_between(x, y1, y2,
                where=(y1 >= y2),         # Condition: fill when y1 is higher than y2
                color='blue', alpha=0.3,
                label='sin ≥ cos')
# Only fill where sin(x) < cos(x) (with a different color)
ax.fill_between(x, y1, y2,
                where=(y1 < y2),
                color='red', alpha=0.3,
                label='sin < cos')

ax.set_title('Conditional Fill with where Parameter')
ax.set_xlabel('x')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

Example 4: fill_betweenx vertical fill

Example

import matplotlib.pyplot as plt
import numpy as np

# The argument order for fill_betweenx is (y, x1, x2)
y = np.linspace(0, 10, 100)
x1 = 2 + np.sin(y)
x2 = 4 + np.cos(y) * 0.5

fig, ax = plt.subplots(figsize=(6, 6), layout='constrained')

ax.fill_betweenx(y, x1, x2, alpha=0.4, color='coral')
ax.plot(x1, y, 'red', linewidth=1.5, label='x1(y)')
ax.plot(x2, y, 'darkred', linewidth=1.5, label='x2(y)')

ax.set_title('fill_betweenx: Vertical Fill')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
plt.show()

Frequently Asked Questions

The data points for the where parameter are not smooth enough?

When the filled area is imprecise at True/False boundaries, setinterpolate=TrueIt can interpolate to compute precise boundaries at intersection points.

What is the difference between fill_between and stackplot?

fill_between()Fills between two specific curves, suitable for showing differences or confidence intervals.

stackplot()Stacks multiple curves layer by layer from 0, suitable for showing the cumulative total of each part.


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions