在单个HH:MM:SS轴上绘制不同日期的数据

2024-09-30 02:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想在一个时间轴上绘制一个不受日期限制的日趋势图。为此,我使用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()

导致以下情节

daily trend time wise

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


Tags: 数据importdataframedfdateindex时间range
2条回答

这个答案可能有点太迟了,但万一有人还在找它。在

这个解决方案适用于不同的月份(如果使用原始问题中的代码,这是一个问题)并保持零时数。在

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()

按如下方式分组后,可以选择索引的hour属性:

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

enter image description here

相关问题 更多 >

    热门问题