通过在没有 for 循环的情况下提取 DatetimeIndex 的时间,在一个图上绘制每一天

Plot each single day on one plot by extracting time of DatetimeIndex without for loop

我有一个包含 7 天随机数据的数据框,每个数据点都由 DatetimeIndex 索引。我想在一个图上绘制每一天的数据。目前我的尝试如下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
n =10000
i = pd.date_range('2018-04-09', periods=n, freq='1min')
ts = pd.DataFrame({'A': [np.random.randn() for i in range(n)]}, index=i)
dates = list(ts.index.map(lambda t: t.date).unique())
for date in dates:
  ts['A'].loc[date.strftime('%Y-%m-%d')].plot()

结果如下:

如您所见,当使用 DatetimeIndex 时,会保留相应的日期,这就是为什么我们每天都回到下一天。

问题:

1- 我如何修复当前代码,使 x 轴从午夜开始到下一个午夜结束。

2- 是否有一种 pandas 方法可以更好地对日期进行分组并在一天内绘制它们而不使用 for 循环?

您可以将索引拆分为日期和时间,并将 ts unstack 拆分为数据帧:

df = ts.set_index([ts.index.date, ts.index.time]).unstack(level=0)
df.columns = df.columns.get_level_values(1)

然后将所有内容绘制在一张图表中:

df.plot()

或在单独的图表中:

axs = df.plot(subplots=True, title=df.columns.tolist(), legend=False, figsize=(6,8))
axs[0].figure.execute_constrained_layout()