Matplotlib fill_between() / fill_betweenx() 函数
fill_between() 用于填充两条水平曲线之间的区域,fill_betweenx() 填充两条垂直曲线之间的区域。
常用于可视化置信区间、不确定性范围、差异区域等。
函数定义
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)
参数说明
| 参数 | 类型 | 说明 |
|---|---|---|
| x / y | array | 第一个坐标轴的数据点 |
| y1, y2 / x1, x2 | array 或 scalar | 两条曲线。标量表示常数线。y2 默认为 0,填充到 x 轴 |
| where | array of bool | 指定哪些区间需要填充。True 填充,False 不填充 |
| interpolate | bool | 若为 True,仅在两条曲线交叉处插值计算精确边界 |
| step | str | 阶梯填充:'pre'、'post'、'mid' |
| color / facecolor | color | 填充颜色 |
| alpha | float | 透明度 |
| label | str | 图例标签 |
| hatch | str | 填充图案:'/'、'\'、'|'、'-'、'+'、'x'、'*' |
fill_between 和 fill_betweenx 返回一个
PolyCollection对象,可用于后续修改或传给 colorbar。
使用示例
示例 1:填充到 x 轴(默认 y2=0)
实例
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')
# 绘制主曲线
ax.plot(x, y, 'b-', linewidth=2, label='sin(x)')
# 填充曲线与 x 轴之间的区域
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()
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots(layout='constrained')
# 绘制主曲线
ax.plot(x, y, 'b-', linewidth=2, label='sin(x)')
# 填充曲线与 x 轴之间的区域
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()
示例 2:置信区间(两条曲线之间的区域)
实例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y_mean = np.sin(x) + 5 # 均值线
y_std = 0.3 + 0.1 * x # 标准差随 x 增大
# 上下界
y_upper = y_mean + y_std
y_lower = y_mean - y_std
fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
# 填充均值两侧的置信区间
ax.fill_between(x, y_lower, y_upper,
alpha=0.3, color='steelblue',
label='Confidence Interval')
# 绘制均值线
ax.plot(x, y_mean, 'steelblue', linewidth=2, label='Mean')
# 绘制上下界
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()
import numpy as np
x = np.linspace(0, 10, 100)
y_mean = np.sin(x) + 5 # 均值线
y_std = 0.3 + 0.1 * x # 标准差随 x 增大
# 上下界
y_upper = y_mean + y_std
y_lower = y_mean - y_std
fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
# 填充均值两侧的置信区间
ax.fill_between(x, y_lower, y_upper,
alpha=0.3, color='steelblue',
label='Confidence Interval')
# 绘制均值线
ax.plot(x, y_mean, 'steelblue', linewidth=2, label='Mean')
# 绘制上下界
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()
示例 3:where 参数条件填充
实例
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)')
# 只在 sin(x) >= cos(x) 的区间填充
ax.fill_between(x, y1, y2,
where=(y1 >= y2), # 条件:y1 高于 y2 时填充
color='blue', alpha=0.3,
label='sin ≥ cos')
# 只在 sin(x) < cos(x) 的区间填充(不同颜色)
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()
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)')
# 只在 sin(x) >= cos(x) 的区间填充
ax.fill_between(x, y1, y2,
where=(y1 >= y2), # 条件:y1 高于 y2 时填充
color='blue', alpha=0.3,
label='sin ≥ cos')
# 只在 sin(x) < cos(x) 的区间填充(不同颜色)
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()
示例 4:fill_betweenx 垂直填充
实例
import matplotlib.pyplot as plt
import numpy as np
# fill_betweenx 的参数顺序是 (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()
import numpy as np
# fill_betweenx 的参数顺序是 (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()
常见问题
where 参数的数据点不够平滑?
当填充区域在 True/False 边界处不精确时,设置 interpolate=True 可以在交叉点处插值计算精确边界。
fill_between 和 stackplot 的区别?
fill_between() 填充两条特定曲线之间,适合展示差值或置信区间。
stackplot() 将多条曲线从 0 开始层层堆叠,适合展示各部分累积总量。

Matplotlib 参考文档