首页 > 解决方案 > 滚动平均值误差

问题描述

我正在尝试在双轴图上绘制滚动平均值。但是,我得到了ValueError: view limit minimum -36867.6 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units错误。我的列中确实有日期时间对象,所以我不确定为什么会这样。

import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

lns1 = ax1.plot(df5['TIME'],
       df5["y"])

lns2 = ax2.plot(df3_plot.rolling(window=3).mean(),
                color='black')

df5 看起来像这样:

    TIME          y
0   1990-01-01  3.380127
1   1990-02-01  3.313274
2   1990-03-01  4.036463
3   1990-04-01  3.813060
4   1990-05-01  3.847867
...
355 2019-08-01  8.590325
356 2019-09-01  7.642616
357 2019-10-01  8.362921
358 2019-11-01  7.696176
359 2019-12-01  8.206370

df3_plot 看起来像这样:

    date           y
0   1994-01-01  239.274414
1   1994-02-01  226.126581
2   1994-03-01  211.591748
3   1994-04-01  214.708679
4   1995-01-01  223.093071
...
99  2018-04-01  181.889699
100 2019-01-01  174.500096
101 2019-02-01  179.803310
102 2019-03-01  175.570419
103 2019-04-01  176.697451

此外,如果我不尝试对df3_plot. 这意味着 x 轴两者的日期时间。当我有

lns2 = ax2.plot(df3_plot['date'],
                df3_plot['y'],
    color='black')

我得到这张图以日期时间为 x 轴的正确图形

编辑

假设 df5 有另一列 'y2' 正确滚动意味着 'y'。如何正确绘制和标记它?我目前有


df6 = df5.rolling(window=12).mean()
lns1 = ax1.plot(
     df6,
    label = 'y',         # how do I add 'y2' label correctly?
    linewidth = 2.0)

df6 看起来像这样:

    TIME    y      y2
0   1990-01-01  NaN     NaN
1   1990-02-01  NaN     NaN
2   1990-03-01  NaN     NaN
3   1990-04-01  NaN     NaN
4   1990-05-01  NaN     NaN
...     ...     ...     ...
355     2019-08-01  10.012447   8.331901
356     2019-09-01  9.909044    8.263813
357     2019-10-01  9.810155    8.185539
358     2019-11-01  9.711690    8.085016
359     2019-12-01  9.619968    8.035330

标签: pythonmatplotlib

解决方案


将“日期”放入我的数据框的索引中起到了作用:df3_plot.set_index('date', inplace=True).

但是,我不确定为什么 @dm2 和我的错误消息不同。


推荐阅读