备注
转到结尾 以下载完整示例代码。
带有误差带的曲线#
此示例展示了如何在参数化曲线周围绘制误差带。
参数化曲线 x(t), y(t) 可以直接使用 plot 绘制。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import PathPatch
from matplotlib.path import Path
N = 400
t = np.linspace(0, 2 * np.pi, N)
r = 0.5 + np.cos(t)
x, y = r * np.cos(t), r * np.sin(t)
fig, ax = plt.subplots()
ax.plot(x, y, "k")
ax.set(aspect=1)

误差带可以用来表示曲线的误差。在这个例子中,我们假设误差可以作为一个标量 err 给出,它描述了曲线在每个点上的垂直不确定性。
我们使用 PathPatch 将此误差可视化为路径周围的一个彩色带。该补丁由两个路径段 (xp, yp) 和 (xn, yn) 创建,它们相对于曲线 (x, y) 垂直偏移 +/- err。
注意:使用 PathPatch 这种方法适用于二维中的任意曲线。如果你只有标准的 y-vs.-x 图,你可以使用更简单的 fill_between 方法(另见 填充两条线之间的区域)。
def draw_error_band(ax, x, y, err, **kwargs):
# Calculate normals via centered finite differences (except the first point
# which uses a forward difference and the last point which uses a backward
# difference).
dx = np.concatenate([[x[1] - x[0]], x[2:] - x[:-2], [x[-1] - x[-2]]])
dy = np.concatenate([[y[1] - y[0]], y[2:] - y[:-2], [y[-1] - y[-2]]])
l = np.hypot(dx, dy)
nx = dy / l
ny = -dx / l
# end points of errors
xp = x + nx * err
yp = y + ny * err
xn = x - nx * err
yn = y - ny * err
vertices = np.block([[xp, xn[::-1]],
[yp, yn[::-1]]]).T
codes = np.full(len(vertices), Path.LINETO)
codes[0] = codes[len(xp)] = Path.MOVETO
path = Path(vertices, codes)
ax.add_patch(PathPatch(path, **kwargs))
_, axs = plt.subplots(1, 2, layout='constrained', sharex=True, sharey=True)
errs = [
(axs[0], "constant error", 0.05),
(axs[1], "variable error", 0.05 * np.sin(2 * t) ** 2 + 0.04),
]
for i, (ax, title, err) in enumerate(errs):
ax.set(title=title, aspect=1, xticks=[], yticks=[])
ax.plot(x, y, "k")
draw_error_band(ax, x, y, err=err,
facecolor=f"C{i}", edgecolor="none", alpha=.3)
plt.show()