You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中SARIMA模型季度销售预测可视化不显示问题求助

SARIMA预测季度销售额可视化问题解决

问题概述

使用截至2017年12月31日的平稳季度销售数据,通过SARIMA模型预测未来一年(2018年)分季度销售额,但运行代码后图例显示预测项,却看不到预测曲线。

代码中的核心问题

  1. 预测时间索引错误:代码中forecast_index起始时间设为2013-01-01,属于历史数据时间范围,而非2018年的未来季度,导致预测曲线绘制在历史数据前方,超出图表显示范围。
  2. 方法名拼写错误:model.Fit()中的Fit首字母大写,应为小写的model.fit(),否则会抛出属性错误导致模型无法训练。
  3. 字符串索引对齐问题:第二次绘图时将索引转为Q{quarter} {year后两位}格式,但预测索引仍对应2013年,与截至2017年的历史数据时间顺序脱节,无法在图表后续位置显示。

修正后的代码

import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.statespace.sarimax import SARIMAX

# 假设order和seasonal_order已提前定义,例如order=(1,1,1), seasonal_order=(1,1,1,4)
model = SARIMAX(quarterly_sales, order=order, seasonal_order=seasonal_order)
results = model.fit()  # 修正首字母大写问题

# 生成2018年4个季度的时间索引(紧跟2017年Q4之后)
forecast_index = pd.date_range(start='2018-01-01', periods=4, freq='Q')
forecast = results.get_forecast(steps=4)
forecast_series = pd.Series(forecast.predicted_mean, index=forecast_index)

# 统一转换为带完整年份的季度字符串索引,确保时间顺序连续
historical_index = [f"Q{date.quarter} {date.year}" for date in quarterly_sales.index]
quarterly_sales.index = historical_index

forecast_index_str = [f"Q{date.quarter} {date.year}" for date in forecast_series.index]
forecast_series.index = forecast_index_str

# 合并历史与预测的索引,保证x轴完整覆盖
all_index = historical_index + forecast_index_str

# 绘图
plt.figure(figsize=(12, 6))
# 绘制历史数据柱状图
plt.bar(historical_index, quarterly_sales, label='Historical Quarterly Sales')
# 绘制预测折线图,用None填充历史数据段,确保曲线从历史末尾开始
plt.plot(all_index, pd.Series([None]*len(historical_index) + list(forecast_series)), 
         color='red', marker='o', linestyle='dashed', linewidth=2, label='Forecasted Quarterly Sales')

plt.title('Quarterly Sales with 2018 Forecast')
plt.xlabel('Quarter')
plt.ylabel('Sales')
plt.xticks(rotation=45)
plt.ylim(0, max(quarterly_sales.max(), forecast_series.max()) * 1.1)
plt.legend()
plt.tight_layout()
plt.show()

关键修正说明

  • 调整预测时间范围:将forecast_index起始时间改为2018-01-01,确保预测的是2018年四个季度,紧跟在2017年历史数据之后。
  • 修复方法名拼写:将model.Fit()改为model.fit(),保证模型正常训练。
  • 对齐索引顺序:合并历史与预测的索引,用None填充历史数据对应的预测位置,让折线图从历史数据末尾开始绘制,确保在图表中可见。

内容的提问来源于stack exchange,提问作者James Stanton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:03:14