备注
前往结尾 以下载完整的示例代码。
填充两条线之间的区域#
这个示例展示了如何使用 fill_between 来为两条线之间的区域着色。
import matplotlib.pyplot as plt
import numpy as np
基本用法#
参数 y1 和 y2 可以是标量,表示在给定的 y 值处的水平边界。如果只给出 y1,则 y2 默认为 0。
x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2 * np.pi * x)
y2 = 0.8 * np.sin(4 * np.pi * x)
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(6, 6))
ax1.fill_between(x, y1)
ax1.set_title('fill between y1 and 0')
ax2.fill_between(x, y1, 1)
ax2.set_title('fill between y1 and 1')
ax3.fill_between(x, y1, y2)
ax3.set_title('fill between y1 and y2')
ax3.set_xlabel('x')
fig.tight_layout()

示例:置信带#
fill_between 的一个常见应用是表示置信带。
fill_between 使用颜色循环中的颜色作为填充颜色。这些颜色在应用于填充区域时可能会显得有些强烈。因此,通常一个好的做法是通过使用 alpha 使区域半透明来使颜色变浅。
N = 21
x = np.linspace(0, 10, 11)
y = [3.9, 4.4, 10.8, 10.3, 11.2, 13.1, 14.1, 9.9, 13.9, 15.1, 12.5]
# fit a linear curve and estimate its y-values and their error.
a, b = np.polyfit(x, y, deg=1)
y_est = a * x + b
y_err = x.std() * np.sqrt(1/len(x) +
(x - x.mean())**2 / np.sum((x - x.mean())**2))
fig, ax = plt.subplots()
ax.plot(x, y_est, '-')
ax.fill_between(x, y_est - y_err, y_est + y_err, alpha=0.2)
ax.plot(x, y, 'o', color='tab:brown')

选择性地填充水平区域#
参数 where 允许指定要填充的 x 范围。它是一个与 x 大小相同的布尔数组。
只有连续的 True 序列的 x 范围被填充。因此,相邻的 True 和 False 值之间的范围永远不会被填充。当数据点应表示连续的数量时,这通常是不希望的。因此,除非数据点的 x 距离足够小,以至于上述效果不明显,否则建议设置 interpolate=True。插值近似于 where 条件将改变的实际 x 位置,并将填充延伸到该位置。
x = np.array([0, 1, 2, 3])
y1 = np.array([0.8, 0.8, 0.2, 0.2])
y2 = np.array([0, 0, 1, 1])
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.set_title('interpolation=False')
ax1.plot(x, y1, 'o--')
ax1.plot(x, y2, 'o--')
ax1.fill_between(x, y1, y2, where=(y1 > y2), color='C0', alpha=0.3)
ax1.fill_between(x, y1, y2, where=(y1 < y2), color='C1', alpha=0.3)
ax2.set_title('interpolation=True')
ax2.plot(x, y1, 'o--')
ax2.plot(x, y2, 'o--')
ax2.fill_between(x, y1, y2, where=(y1 > y2), color='C0', alpha=0.3,
interpolate=True)
ax2.fill_between(x, y1, y2, where=(y1 <= y2), color='C1', alpha=0.3,
interpolate=True)
fig.tight_layout()

备注
如果 y1 或 y2 是掩码数组,类似的间隙也会出现。由于缺失值无法近似,interpolate 在这种情况下无效。掩码值周围的间隙只能通过在掩码值附近添加更多数据点来减少。
在整个 Axes 中有选择地标记水平区域#
相同的选取机制可以应用于填充Axes的整个垂直高度。为了不受y轴限制的影响,我们添加了一个变换,该变换将x值解释为数据坐标,将y值解释为Axes坐标。
以下示例标记了 y 数据高于给定阈值的区域。
fig, ax = plt.subplots()
x = np.arange(0, 4 * np.pi, 0.01)
y = np.sin(x)
ax.plot(x, y, color='black')
threshold = 0.75
ax.axhline(threshold, color='green', lw=2, alpha=0.7)
ax.fill_between(x, 0, 1, where=y > threshold,
color='green', alpha=0.5, transform=ax.get_xaxis_transform())

参考文献
以下示例展示了以下函数、方法、类和模块的使用: