【问题标题】:Superposing Pandas time series from different years in Seaborn plot在 Seaborn 图中叠加不同年份的 Pandas 时间序列
【发布时间】:2017-11-26 01:39:01
【问题描述】:

我有一个 Pandas 数据框,我想探索时间序列的周期性、趋势等。 Here 是数据。

为了可视化它,我想将每年的“子时间序列”叠加在同一个图上(即,对于 01/01/2000、01/01/2001 和 01/01/ 的数据具有相同的 x 坐标) 2002)。

我是否必须转换我的日期列以使每个数据具有相同的年份?

有人知道怎么做吗?

【问题讨论】:

    标签: python date pandas time-series seaborn


    【解决方案1】:

    设置
    这会解析您链接的数据

    df = pd.read_csv(
        'data.csv', sep=';', decimal=',',
        usecols=['date', 'speed', 'height', 'width'],
        index_col=0,  parse_dates=[0]
    )
    

    我的黑客
    我从日期中去掉了除年份以外的所有内容,并假定为 2012 的年份,因为它是闰年,将容纳 2 月 29 日。我将这一年拆分为另一个级别的多索引,unstackplot

    idx = pd.MultiIndex.from_arrays([
            pd.to_datetime(df.index.strftime('2012-%m-%d %H:%M:%S')),
            df.index.year
        ])
    
    ax = df.set_index(idx).unstack().speed.plot()
    lg = ax.legend(bbox_to_anchor=(1.05, 1), loc=2, ncol=2)
    


    为了美化这一点

    fig, axes = plt.subplots(3, 1, figsize=(15, 9))
    
    idx = pd.MultiIndex.from_arrays([
            pd.to_datetime(df.index.strftime('2012-%m-%d %H:%M:%S')),
            df.index.year
        ])
    
    d1 = df.set_index(idx).unstack().resample('W').mean()
    d1.speed.plot(ax=axes[0], title='speed')
    lg = axes[0].legend(bbox_to_anchor=(1.02, 1), loc=2, ncol=1)
    
    d1.height.plot(ax=axes[1], title='height', legend=False)
    d1.width.plot(ax=axes[2], title='width', legend=False)
    
    fig.tight_layout()
    

    【讨论】:

      【解决方案2】:

      您可以这样做的一种方法是为所有年份创建一个公共 x 轴,如下所示:

      df['yeartime']=df.groupby(df.date.dt.year).cumcount()
      

      其中 'yeartime' 表示一年中时间度量的数量。接下来,创建一个年份列:

      df['year'] = df.date.dt.year
      

      现在,让我们对 2000 年、2001 年和 2002 年 1 月 1 日的数据进行子集化

      subset_df = df.loc[df.date.dt.year.isin(['2000','2001',2002]) & (df.date.dt.day == 1) & (df.date.dt.month == 1)]
      

      最后,绘制它。

      ax = sns.pointplot('yeartime','speed',hue='year',data=subset_df, markers='None')
      _ =ax.get_xaxis().set_ticks([])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-04
        • 2015-05-13
        • 2020-04-25
        • 2021-12-07
        • 2017-10-16
        • 1970-01-01
        • 2019-05-06
        • 1970-01-01
        相关资源
        最近更新 更多