【问题标题】:How to leave gaps in plot of incomplete timeseries?如何在不完整的时间序列图中留下空白?
【发布时间】:2022-01-20 07:51:27
【问题描述】:

我正在绘制有间隙的时间序列。观测来自 6 个不同的日期,每天连续数据点之间的延迟平均约为 10 秒。

在某些日子观察窗口只是一天的一部分,例如从 00:00 到 7:40,这导致包含所有日期的合并序列中存在巨大差距。我想绘制合并数据,但将天数留空。相反,现在有某种线性插值 - 在下图中,您可以看到数据的蓝色图和 x 轴值上方的红点,这些值确实存在于数据中:

我发现它具有误导性,例如,有时间隙中的线在 y = 0 上,因此我最初认为该设备(这是功耗数据)在该期间处于非活动状态并且 y 的值为 0(实际上我们根本没有那个时期的数据)。

如何防止 matplotlib 在间隙中绘制线条?这就是我创建蓝色图的方式:

dev_data.plot(kind = "line", ax = axes[0], legend = None, title = "Device data")

编辑:我发现有人有相反的问题。我希望我的情节看起来像this question,但我不知道我应该在我的代码中更改什么。

【问题讨论】:

    标签: python matplotlib time-series timeserieschart gaps-in-visuals


    【解决方案1】:

    Matplotlib 不会打印缺失的(NaN 或掩码)值,请参阅demo

    要使用它,您需要找到间隙(例如,时间戳之间的差异 > 10 秒)并在这些间隙内的时间戳处添加额外的 NaN 值。

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    idx = np.concatenate((pd.date_range('2011-04-17', periods=200, freq='10S'),
                          pd.date_range('2011-04-18', periods=100, freq='10S'),
                          pd.date_range('2011-04-19', periods=300, freq='10S')))
    s = pd.Series(np.random.rand(len(idx)), index=idx)
    
    fig, (ax1,ax2) = plt.subplots(2, layout='constrained')
    s.plot(ax=ax1, legend=None, title="Original without gaps")
    
    # positions with gaps > 10 s
    gaps = np.flatnonzero(np.diff(s.index) > np.timedelta64(10, 's'))
    
    # add empty values at gap start positions + 1 s
    s1 = s.append(pd.Series(index=s[gaps].index + np.timedelta64(1, 's'), dtype=float))
    
    s1.plot(ax=ax2, legend=None, title="With gaps")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多