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

Python时间序列图表显示异常问题求助

Python时间序列图表显示异常问题求助

嗨,我来帮你排查下图表显示异常的可能原因~先理清楚你的场景:

你正在做时间序列练习,手上有一组月度数据,结构如下:

date(indexed)YearSalary
2000-04-302000274633
2000-05-312000256064
.........
2023-01-312023535791
2023-02-282023375202

你想要绘制薪资的变化趋势,同时做时间序列分解,但所有图表都显示混乱,使用的代码如下:

def seasonal_decomposition(data, column, periode, title, name):
    decomposition = seasonal_decompose(data[column], period=periode)
    seasonal = decomposition.seasonal
    trend = decomposition.trend
    resid = decomposition.resid

    plt.figure(1 , figsize =(12,8))
    plt.plot(data.index, data[column], 'k')
    plt.legend([column])
    plt.xlabel("Years")
    plt.ylabel(column)
    plt.title(title)

    plt.figure(2 , figsize =(20,13))
    plt.suptitle(" Trend, Seasonality and Residuals of the " + column + " time series")
    plt.subplot(2, 2, 1)
    plt.plot(data.index,trend)
    plt.xlabel("Years")
    plt.ylabel(column + name)
    plt.title("The Trend of" + name )

    plt.subplot(2, 2, 2)
    plt.plot(data.index,seasonal)
    plt.xlabel("Years")
    plt.ylabel(column + name)
    plt.title("Seasonality" + name )

    plt.subplot(2, 2, 3)
    plt.plot(data.index,resid)
    plt.xlabel("Years")
    plt.ylabel(column + name)
    plt.title("Residuals" + name )

    plt.subplot(2, 2, 4)
    plt.plot(data.index,trend)
    plt.plot(data.index,seasonal)
    plt.plot(data.index,resid)
    plt.title("All of the components")
    plt.legend(['Trend', 'Seasonal', 'Residuals'],loc='lower left')
    plt.show()

你表示完全不清楚为什么图表会显示异常,所有函数内的图表都有同样的问题。下面是几个大概率的排查方向:

  • 日期索引格式问题:首先检查你的日期索引是不是正确的datetime类型,如果只是字符串格式,matplotlib无法正确解析时间轴,会导致图表的x轴混乱。可以用data.index = pd.to_datetime(data.index)转换格式,同时确认索引是单调递增的(没有日期乱序的情况)。
  • 周期参数设置错误:seasonal_decompose的period参数需要匹配数据频率,你的数据是月度数据,正常应该设为12(对应一年12个月)。如果传入的periode值不对,分解出来的趋势、季节性会完全失真,进而导致图表异常。
  • 数据异常值影响:检查薪资数据中是否存在极端异常值(比如突然出现的超大/超小数值),这类值会拉伸y轴范围,让图表看起来混乱。可以先运行data['Salary'].describe()查看数据的统计特征,确认是否有异常。
  • 先做最小化调试:先抛开这个函数,单独绘制原始薪资数据:
    import matplotlib.pyplot as plt
    plt.plot(data.index, data['Salary'])
    plt.show()
    
    如果这个简单图表依然混乱,问题大概率出在日期索引或数据本身;如果这个图表正常,再去排查seasonal_decompose的参数和分解结果是否正确。

备注:内容来源于stack exchange,提问作者Sofiane AMIROUCHE

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 14:18:05