如何绘制 Python 中时间序列数据的置信区间?

How to plot confidence interval of a time series data in Python?

这方面存在多个问题,但我不能用它们来解决我的问题。我有一个数据样本,我想为其曲线创建置信区间。在这里,我提供一个简单的例子:

import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt

mean, lower, upper = [],[],[]
ci = 0.2
for i in range (20):

    a = np.random.rand(100) # this is the output

    MEAN = np.mean(a)
    mean.append(MEAN)
    std = np.std(a)
    Upper = MEAN+ci*std
    Lower = MEAN-ci*std

    lower.append(Lower)
    upper.append(Upper)


 plt.figure(figsize=(20,8))
 plt.plot(mean,'-b', label='mean')
 plt.plot(upper,'-r', label='upper')
 plt.plot(lower,'-g', label='lower')

 plt.xlabel("Value",   fontsize = 30)
 plt.ylabel("Loss", fontsize = 30)
 plt.xticks(fontsize= 30) 
 plt.yticks(fontsize= 30) 
 plt.legend(loc=4, prop={'size': 30})

在上面的例子中,我画了%80的置信区间。我有两个问题:

1- 你能告诉我这种计算和绘制置信区间的方法是正确的吗?

2- 我想给置信区间的阴影区域上色。我附上了一个数字,我想要这样的东西。你能告诉我你有什么解决办法吗?感谢您的帮助。

我没有资格回答问题 1,但是这个 SO question 的答案与您的代码产生不同的结果。

关于问题2,您可以使用matplotlib fill_between 填充两条曲线之间的区域(您的示例的上部和下部)。

import numpy as np
import matplotlib.pyplot as plt
import scipy.stats

# 
def mean_confidence_interval(data, confidence=0.95):
    a = 1.0 * np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
    return m, m-h, m+h

mean, lower, upper = [],[],[]
ci = 0.8
for i in range (20):
    a = np.random.rand(100) # this is the output
    m, ml, mu = mean_confidence_interval(a, ci)
    mean.append(m)
    lower.append(ml)
    upper.append(mu)

plt.figure()
plt.plot(mean,'-b', label='mean')
plt.plot(upper,'-r', label='upper')
plt.plot(lower,'-g', label='lower')
# fill the area with black color, opacity 0.15
plt.fill_between(list(range(len(mean))), upper, lower, color="k", alpha=0.15)

plt.xlabel("Value")
plt.ylabel("Loss")
plt.legend()