Skip to content

Instantly share code, notes, and snippets.

@cwindolf
Created September 12, 2024 21:01
Show Gist options
  • Save cwindolf/6fd6e9a180095546a2135ab5e66de3dd to your computer and use it in GitHub Desktop.
Save cwindolf/6fd6e9a180095546a2135ab5e66de3dd to your computer and use it in GitHub Desktop.
Plot moving means and standard deviations
def sliding_mean_and_stddev_interval(
axis, xs, ys, n_neighbors=30, linewidth=1, color="k", ci_alpha=0.25
):
"""Plot moving means and standard deviations"""
_1 = np.ones(2 * n_neighbors + 1)
_ys = np.nan_to_num(ys)
sliding_sum = correlate1d(_ys, _1, mode="constant")
sliding_N = correlate1d(np.isfinite(ys).astype(float), _1, mode="constant")
sliding_mean = sliding_sum / sliding_N
sliding_sumsq = correlate1d(_ys**2, _1, mode="constant")
sliding_std = np.sqrt(sliding_sumsq / sliding_N - sliding_mean**2)
if ci_alpha:
ci = axis.fill_between(
xs,
sliding_mean - sliding_std,
sliding_mean + sliding_std,
color=color,
alpha=ci_alpha,
edgecolor=None,
)
line = axis.plot(xs, sliding_mean, color=color, linewidth=linewidth)
return line, ci, sliding_mean, sliding_std, sliding_N
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment