python 给时间序列加误差线
时间: 2023-07-20 13:11:54 浏览: 156
在Python中,可以使用Matplotlib库中的`errorbar()`函数给时间序列加上误差线。
假设我们有一个时间序列的数据,其中包含了每天的销售额,我们想要给这个时间序列加上每天的销售额的置信区间作为误差线。我们可以按照以下步骤实现:
1. 首先,我们需要计算每天销售额的平均值和标准差,以及置信区间。
```python
import numpy as np
import pandas as pd
import statsmodels.api as sm
# 生成时间序列数据
np.random.seed(123)
n = 365
sales_data = [np.random.normal(100, 20) for _ in range(n)]
sales_ts = pd.Series(sales_data, index=pd.date_range('20210101', periods=n, freq='D'))
# 计算每天销售额的平均值和标准差,以及置信区间
sales_mean = sales_ts.mean()
sales_std = sales_ts.std()
ci = sm.stats.DescrStatsW(sales_data).tconfint_mean(alpha=0.05)
```
2. 接下来,我们可以使用`errorbar()`函数绘制误差线。需要注意的是,`errorbar()`函数需要传入x轴和y轴的数据,以及误差线的上下限。
```python
import matplotlib.pyplot as plt
# 绘制时间序列图和误差线
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(sales_ts.index, sales_ts.values, label='Sales')
ax.errorbar(sales_ts.index, sales_ts.values, yerr=sales_std, fmt='-o', label='Standard Deviation')
ax.fill_between(sales_ts.index, ci[0], ci[1], alpha=0.2, color='gray', label='95% CI')
ax.legend(loc='best')
ax.set_xlabel('Date')
ax.set_ylabel('Sales')
ax.set_title('Sales with Error Bars')
plt.show()
```
在上述代码中,`errorbar()`函数的参数`fmt`指定了误差线的样式,如`'-'`表示实线,`'--'`表示虚线,`'o'`表示圆点,等等。`fill_between()`函数用于填充置信区间,其中`alpha`参数指定了填充颜色的透明度。
运行上述代码,即可得到加上误差线的时间序列图。
阅读全文
相关推荐
















