【问题标题】:plotting data for different days on a single HH:MM:SS axis在单个 HH:MM:SS 轴上绘制不同日期的数据
【发布时间】:2015-02-20 14:32:12
【问题描述】:

DataFrame 有时间戳数据,我想直观地比较数据的每日时间演变。如果我groupby day 并绘制图表;由于日期的不同,它们显然在时间上水平位移。

我想在仅时间轴上绘制与日期无关的日期趋势图。为此,我使用shift将数据返回适当的天数,如以下代码所示

import pandas as pd
import datetime
import matplotlib.pyplot as plt

index1 = pd.date_range('20141201', freq='H', periods=2)
index2 = pd.date_range('20141210', freq='2H', periods=4)
index3 = pd.date_range('20141220', freq='3H', periods=5)

index = index1.append([index2, index3])

df = pd.DataFrame(list(range(1, len(index)+1)), index=index, columns=['a'])

gbyday = df.groupby(df.index.day)

first_day = gbyday.keys.min() # convert all data to this day

plt.figure()
ax = plt.gca()
for n,g in gbyday:
    g.shift(-(n-first_day+1), 'D').plot(ax=ax, style='o-', label=str(n))

plt.show()

导致以下情节

问题:这是熊猫的做法吗?换句话说,我怎样才能更优雅地实现这一点?

【问题讨论】:

    标签: python pandas time-series timeserieschart


    【解决方案1】:

    这个答案可能为时已晚,但万一有人还在寻找它。

    此解决方案适用于不同月份(如果使用原始问题中的代码,则会出现问题)并保留小数小时。

    import pandas as pd
    import matplotlib.pyplot as plt
    
    index0 = pd.date_range('20141101', freq='H', periods=2)
    index1 = pd.date_range('20141201', freq='H', periods=2)
    index2 = pd.date_range('20141210', freq='2H', periods=4)
    index3 = pd.date_range('20141220', freq='3H', periods=5)
    
    index = index1.append([index2, index3, index0])
    df = pd.DataFrame(list(range(1, len(index)+1)), index=index, columns=['a'])
    
    
    df['time_hours'] = (df.index - df.index.normalize()) / pd.Timedelta(hours=1)
    
    fig, ax = plt.subplots()
    for n,g in df.groupby(df.index.normalize()):
        ax.plot(g['time_hours'], g['a'], label=n, marker='o')
    
    ax.legend(loc='best')
    plt.show()
    

    【讨论】:

      【解决方案2】:

      这样分组后可以选择索引的hour属性:

      In [36]: fig, ax = plt.subplots()
      In [35]: for label, s in gbyday:
         ....:     ax.plot(s.index.hour, s, 'o-', label=label)
      

      【讨论】:

      • 此解决方案丢弃了“分钟”和“秒”信息,因此该图仅包含每小时趋势。当然,我知道可以使用s.index.hour、s.index.minute 等创建多索引,但这与我的问题中的代码一样多。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 1970-01-01
      相关资源
      最近更新 更多