如何在Python中绘制带有置信区间的时间序列数组?(Matplotlib)

如何在Python中绘制带有置信区间的时间序列数组?(Matplotlib)

时间序列是我们在许多领域中都会遇到的数据类型,例如股票价格、天气预报和地震振动等。为了更好地对时间序列数据进行分析,我们有时需要绘制带有置信区间的图表。这篇文章将介绍如何在 Python 中使用 Matplotlib 绘制带有置信区间的时间序列数组。

准备数据

我们首先需要准备时间序列数据。在本文中,我们将使用 Pandas 生成一些随机数据。

import pandas as pd
import numpy as np

# 创建时间序列数据
dates = pd.date_range('20210101', periods=100)
data = np.random.randn(100)
df = pd.DataFrame({'price': data}, index=dates)

这里我们使用 pd.date_range 创建了一个包含 100 个日期的时间序列,然后使用 np.random.randn 生成一些随机数,并将它们存储在 Pandas DataFrame 中。

绘制基础图表

要绘制带有置信区间的时间序列图表,我们首先需要绘制基础图表。下面的代码段演示了如何在 Matplotlib 中绘制线性时间序列图表。

import matplotlib.pyplot as plt

plt.plot(df.index, df['price'])
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Time Series Plot')
plt.show()

请注意,我们将 DataFrame 的索引用作 x 轴,而 ‘price’ 列用作 y 轴。运行此代码将生成基础图表。

计算置信区间

接下来,我们需要计算置信区间。在统计学中,置信区间指的是一个范围,该范围内包含真实参数的值的可能性较高。在时间序列图表中,我们经常使用 95% 置信区间。换句话说,我们希望可视化的图表中包含 95% 的观测值。

计算置信区间的一种方法是使用滚动均值和滚动标准差。以下代码段演示了如何在 Pandas 中进行此计算。

# 计算滚动均值和滚动标准差
rolling_mean = df['price'].rolling(window=20).mean()
rolling_std = df['price'].rolling(window=20).std()

# 计算置信区间
upper_band = rolling_mean + (rolling_std * 2)
lower_band = rolling_mean - (rolling_std * 2)

这里我们使用 rolling 函数计算滚动均值和滚动标准差。之后,我们计算了上下置信区间。通过将滚动均值与 2 倍滚动标准差相加和相减,我们得到 95% 置信区间。

绘制置信区间

现在我们已经计算了置信区间,我们可以使用 Matplotlib 将其绘制在时间序列图表中。以下代码段演示了如何绘制置信区间。

plt.plot(df.index, df['price'], label='Price')
plt.plot(rolling_mean.index, rolling_mean, label='Rolling Mean')
plt.fill_between(upper_band.index, upper_band, lower_band, color='grey', alpha=0.2, label='Confidence Interval')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Time Series Plot with Confidence Interval')
plt.legend()
plt.show()

这里我们将 DataFrame 的索引和 ‘price’ 列用于绘制价格折线图。之后,我们绘制了滚动均值折线图。最后,我们使用 fill_between 函数绘制了置信区间。为了使置信区间更加显眼,我们选择了较浅的灰色填充,并解释了该区域是置信区间。运行此代码将生成带有置信区间的时间序列图表。

完整代码

最终代码如下,它包含了上述示例代码和计算置信区间的部分。

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

# 创建时间序列数据
dates = pd.date_range('20210101', periods=100)
data = np.random.randn(100)
df = pd.DataFrame({'price': data}, index=dates)

# 计算滚动均值和滚动标准差
rolling_mean = df['price'].rolling(window=20).mean()
rolling_std = df['price'].rolling(window=20).std()

# 计算置信区间
upper_band = rolling_mean + (rolling_std * 2)
lower_band = rolling_mean - (rolling_std * 2)

# 绘制时间序列图表
plt.plot(df.index, df['price'], label='Price')
plt.plot(rolling_mean.index, rolling_mean, label='Rolling Mean')
plt.fill_between(upper_band.index, upper_band, lower_band, color='grey', alpha=0.2, label='Confidence Interval')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Time Series Plot with Confidence Interval')
plt.legend()
plt.show()

结论

Python 中使用 Matplotlib 绘制带有置信区间的时间序列图表是一个有用的数据分析工具。本文提供了具体步骤和示例代码,希望读者能够运用这些知识去进行自己的数据分析工作。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程