如何在 python 中绘制显示置信区间的时间序列数组?

How to plot a time series array, with confidence intervals displayed, in python?

我有一些缓慢增加的时间序列,但在很短的时间内它们非常波动。例如,时间序列可能如下所示:

[10 + np.random.rand() for i in range(100)] + [12 + np.random.rand() for i in range(100)] + [14 + np.random.rand() for i in range(100)] 

我想绘制时间序列,重点关注大趋势,而不是小波浪。有没有一种方法可以绘制一段时间内的平均值,周围有一条指示波浪的条纹(条纹应该代表置信区间,数据点可能在那一刻)?

一个简单的情节看起来像这样:

我想要的带有置信区间的图如下所示:

在 Python 中有没有一种优雅的方式来做到这一点?

您可以使用 pandas 函数 rolling(n) 生成 n 个连续点的平均值和标准偏差值。

对于置信区间的阴影(由标准差之间的 space 表示),您可以使用 matplotlib.pyplot 中的函数 fill_between()。有关详细信息,您可以查看 here,以下代码的灵感来自于此。

import numpy             as np
import pandas            as pd
import matplotlib.pyplot as plt

#Declare the array containing the series you want to plot. 
#For example:
time_series_array = np.sin(np.linspace(-np.pi, np.pi, 400)) + np.random.rand((400))
n_steps           = 15 #number of rolling steps for the mean/std.

#Compute curves of interest:
time_series_df = pd.DataFrame(time_series_array)
smooth_path    = time_series_df.rolling(n_steps).mean()
path_deviation = 2 * time_series_df.rolling(n_steps).std()

under_line     = (smooth_path-path_deviation)[0]
over_line      = (smooth_path+path_deviation)[0]

#Plotting:
plt.plot(smooth_path, linewidth=2) #mean curve.
plt.fill_between(path_deviation.index, under_line, over_line, color='b', alpha=.1) #std curves.

使用上面的代码你会得到这样的东西:

看起来,您将 std 加倍了两次。我想应该是这样的:

time_series_df = pd.DataFrame(time_series_array)
smooth_path = time_series_df.rolling(20).mean()
path_deviation = time_series_df.rolling(20).std()
plt.plot(smooth_path, linewidth=2)
plt.fill_between(path_deviation.index, (smooth_path-2*path_deviation)[0], (smooth_path+2*path_deviation)[0], color='b', alpha=.1)