plt.figure() #新开一个图窗 diff1=data.diff(1) plt.plot(diff1,label='一阶') diff2=data.diff(2) plt.plot(diff2,label='二阶') plt.legend()
时间: 2024-05-25 14:12:47 浏览: 12
这段代码使用了Python中的matplotlib库绘制图形。具体来说:
- `plt.figure()` 创建一个新的图窗。
- `diff1=data.diff(1)` 计算数据`data`的一阶差分。
- `plt.plot(diff1,label='一阶')` 绘制一阶差分的曲线,并设置标签为“一阶”。
- `diff2=data.diff(2)` 计算数据`data`的二阶差分。
- `plt.plot(diff2,label='二阶')` 绘制二阶差分的曲线,并设置标签为“二阶”。
- `plt.legend()` 显示标签。
综合起来,这段代码的作用是绘制数据的一阶和二阶差分曲线,并在图形中显示标签。
相关问题
sales = list(np.diff(data["#Passengers"])) data2 = { "Month":data1.index[1:], #1月1日是空值,从1月2号开始取 "#Passengers":sales } df = pd.DataFrame(data2) df['Month'] = pd.to_datetime(df['Month']) #df[''date]数据类型为“object”,通过pd.to_datetime将该列数据转换为时间类型,即datetime。 data_diff = df.set_index(['Month'], drop=True) #将日期设置为索引 data_diff.head() print(data_diff) fig = plt.figure(figsize=(12,8)) ax1=fig.add_subplot(211) fig = sm.graphics.tsa.plot_acf(data_diff,lags=20,ax=ax1) ax2 = fig.add_subplot(212) fig = sm.graphics.tsa.plot_pacf(data_diff,lags=20,ax=ax2) plt.show() # 为了控制计算量,我们限制AR最大阶不超过6,MA最大阶不超过4。 sm.tsa.arma_order_select_ic(data_diff,max_ar=100,max_ma=4,ic='aic')['aic_min_order'] # AIC ''' #对模型进行定阶 pmax = int(len(df) / 10) #一般阶数不超过 length /10 qmax = int(len(df) / 10) bic_matrix = [] for p in range(pmax +1): temp= [] for q in range(qmax+1): try: temp.append(ARIMA(data, (p, 1, q)).fit().bic) except: temp.append(None) bic_matrix.append(temp) bic_matrix = pd.DataFrame(bic_matrix) #将其转换成Dataframe 数据结构 p,q = bic_matrix.stack().idxmin() #先使用stack 展平, 然后使用 idxmin 找出最小值的位置 print(u'BIC 最小的p值 和 q 值:%s,%s' %(p,q)) # BIC 最小的p值 和 q 值:0,1 #所以可以建立ARIMA 模型,ARIMA(0,1,1) ''' model = ARIMA(data, (0,1,1)).fit() #model.summary2() predictions_ARIMA_diff = pd.Series(model.fittedvalues, copy=True) print("========") print(predictions_ARIMA_diff.head()) exit() plt.figure(figsize=(10, 6)) plt.plot(predictions_ARIMA_diff,label="forecast_diff") plt.plot(data_diff,label="diff") plt.xlabel('日期',fontsize=12,verticalalignment='top') plt.ylabel('销量差分',fontsize=14,horizontalalignment='center') plt.legend() plt.show()
这段代码首先计算了原始数据的一阶差分,并将差分后的销量数据存储在一个名为"sales"的列表中。然后,根据差分后的销量数据创建了一个新的DataFrame,并将日期列转换为Datetime格式。接下来,将日期列设置为索引,并打印出数据的前几行。
然后,代码绘制了差分后销量数据的自相关性(ACF)和偏自相关性(PACF)图。图形显示了滞后项与自相关系数/偏自相关系数之间的关系。
接下来,代码使用ARMA模型的AIC准则进行了模型定阶。限制了AR最大阶不超过6,MA最大阶不超过4。
然后,代码建立了ARIMA(0,1,1)模型,并使用该模型对差分后的数据进行了拟合。拟合后得到的值存储在predictions_ARIMA_diff中,并打印出前几行。
最后,代码绘制了拟合值和差分后数据的图形,并使用exit()函数退出程序。
import pandas as pd import numpy as np import matplotlib.pyplot as plt from statsmodels.tsa.arima.model import ARIMA from statsmodels.graphics.tsaplots import plot_acf, plot_pacf plt.rcParams['font.sans-serif']=['SimHei'] import matplotlib as mpl mpl.rcParams['axes.unicode_minus'] = False import warnings warnings.filterwarnings("ignore") years = range(1997, 2004) months = range(1, 13) data = [ [9.4, 11.3, 16.8, 19.8, 20.3, 18.8, 20.9, 24.9, 24.7, 24.3, 19.4, 18.6], [9.6, 11.7, 15.8, 19.9, 19.5, 17.8, 17.8, 23.3, 21.4, 24.5, 20.1, 15.9], [10.1, 12.9, 17.7, 21, 21, 20.4, 21.9, 25.8, 29.3, 29.8, 23.6, 16.5], [11.4, 26, 19.6, 25.9, 27.6, 24.3, 23, 27.8, 27.3, 28.5, 32.8, 18.5], [11.5, 26.4, 20.4, 26.1, 28.9, 28, 25.2, 30.8, 28.7, 28.1, 22.2, 20.7], [13.7, 29.7, 23.1, 28.9, 29, 27.4, 26, 32.2, 31.4, 32.6, 29.2, 22.9], [15.4, 17.1, 23.5, 11.6, 1.78, 2.61, 8.8, 16.2, None, None, None, None] ] df = pd.DataFrame(data, columns=range(1, 13), index=range(1997, 2004)) df.index.name = '年份' # 平稳性检验 def test_stationarity(timeseries): # 将数组转换为 Series 对象 series = pd.Series(timeseries) # 计算移动平均和移动标准差 rolling_mean = series.rolling(window=3).mean() rolling_std = series.rolling(window=3).std() # 绘制移动平均和移动标准差 plt.figure(figsize=(10, 6),dpi=500) plt.plot(series.values.flatten(), label='原始数据') plt.plot(rolling_mean.values.flatten(), label='移动平均') plt.plot(rolling_std.values.flatten(), label='移动标准差') plt.xlabel('月数') plt.ylabel('接待人数(万人)') plt.title('移动平均和移动标准差') plt.legend() plt.show() # 执行ADF单位根检验 from statsmodels.tsa.stattools import adfuller result = adfuller(series.dropna()) print('ADF检验结果:') print(f'ADF统计量: {result[0]}') print(f'p-value: {result[1]}') print(f'临界值: {result[4]}') # 进行平稳性检验 test_stationarity(df.stack().values.flatten()) # 差分处理 df_diff = df.diff().dropna()
这段代码是一个Python程序,它的功能是进行时间序列分析。首先,导入了一些必要的模块和库,如pandas、numpy、matplotlib等。然后,定义了一个二维数组data,并将其转换为pandas的DataFrame格式。接下来,定义了一个名为test_stationarity的函数,用于检验时间序列的平稳性。具体而言,该函数计算了时间序列的移动平均和移动标准差,并绘制了它们的图形,然后执行ADF单位根检验,以确定时间序列是否平稳。最后,对原始数据进行了差分处理,并保存在新的DataFrame df_diff中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)