如何在 pandas 数据框中绘制一天中每个小时发生的事件数?

How to plot number of events occurring at each hour of the day in a pandas dataframe?

假设我有以下数据:

import pandas as pd
data = {'time':[7, 1, 2, 7, 2, 2, 1, 2, 7, 3, 5], 'event':['a', 'b', 'a', 'a', 'b', 'a', 'a', 'b', 'b', 'b', 'a']}
df = pd.DataFrame(data)

我想显示一天中每个小时发生的每种类型的事件数。但是,数据集的“时间”列中只有 5 个唯一时间。

当数据集中存在一天中所有 24 个不同的小时(1 到 24)时,使用 bins=24 绘制直方图有效。但是,如果一天中只有几个小时存在,则直方图不会执行此任务。

例如,使用上述数据,代码 df.hist() 生成此图表:

不清楚 x 轴刻度的确切位置 - 我想要的是,此图表中的 5 个尖峰应位于 x = 1、2、3、5 和 7,并且应该有在 x = 4、6 和 8 到 24 处没有尖峰。

加上df.time.hist(bins=24),生成如下图表:

这里好一点,因为我们可以看到至少前 4 个尖峰位于 x = 1、2、3 和 5,x = 4 和 x = 6 留空。但是,在 x=7 时,尖峰绘制在网格线的左侧,而其他 4 个尖峰绘制在网格线的右侧。此外,这不会显示 x = 8 到 24 处的空尖峰。

那么,我该怎么做呢?

试试这个:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = {'time':[7, 1, 2, 7, 2, 2, 1, 2, 7, 3, 5], 'event':['a', 'b', 'a', 'a', 'b', 'a', 'a', 'b', 'b', 'b', 'a']}
df = pd.DataFrame(data)
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(16, 10))

df.hist(ax=axes, bins=range(24))

# offset the xticks
axes.set_xticks(np.arange(24) + .5)

# name the label accordingly
axes.set_xticklabels(range(24))