首页 > 解决方案 > Pandas df histo,格式化我的 x 代码并包含空

问题描述

我得到了这个熊猫df:

index      TIME
12:07      2019-06-03  12:07:28
10:04      2019-06-04  10:04:25
11:14      2019-06-09  11:14:25
...

我使用这个命令做一个直方图来绘制每 15 分钟周期的发生次数

df['TIME'].groupby([df["TIME"].dt.hour, df["TIME"].dt.minute]).count().plot(kind="bar")

我的情节是这样的:

在此处输入图像描述

我怎样才能得到像 10:15 这样的 x 刻度来代替 (10, 15) 以及如何设法添加像 9:15, 9:30... 这样丢失的 x 刻度以获得完整的时间线?

标签: pandasmatplotlibplotgroup-byticker

解决方案


您可以resampleTIME列间隔为 15 分钟并计算行数。然后绘制一个常规条形图。

df = pd.DataFrame({'TIME': pd.to_datetime('2019-01-01') + pd.to_timedelta(pd.np.random.rand(100) * 3, unit='h')})
df = df[df.TIME.dt.minute > 15] # make gap

ax = df.resample('15T', on='TIME').count().plot.bar(rot=0)
ticklabels = [x.get_text()[-8:-3] for x in ax.get_xticklabels()]
ax.xaxis.set_major_formatter(matplotlib.ticker.FixedFormatter(ticklabels))

(有关格式化熊猫条形图的日期时间刻度标签的详细信息,请参阅此问题

在此处输入图像描述


推荐阅读