首页 > 解决方案 > 每小时直方图 - matplotlib

问题描述

我正在分析英国交通事故的公共数据。

我的数据框如下所示:

Index     Time

0         02:30
1         00:37
2         01:25
3         09:15
4         07:53
5         09:29
6         08:53
7         10:05

我正在尝试绘制一个直方图,显示一天中的事故分布,这是我的代码:

  import matplotlib
  import matplotlib.pyplot as plt
  import numpy as np
  import datetime as dt
  import matplotlib.dates as mdates
  df['hour']=pd.to_datetime(df['Time'],format='%H:%M')
  df.set_index('hour', drop=False, inplace=True)
  df['hour'].groupby(pd.Grouper(freq='60Min')).count().plot(kind='bar', color='b')

这是输出:

图形

在此图中,我想将 x 轴上的标签更改为格式“hh:mm”。我该怎么做呢?

标签: pythonmatplotlibhistogrampandas-groupby

解决方案


您缺少的是设置 matplotlib x 轴格式的格式:

df.set_index('hour', drop=False, inplace=True)
df = df['hour'].groupby(pd.Grouper(freq='60Min')).count()
ax = df.plot(kind='bar', color='b')
ticklabels = df.index.strftime('%H:%Mh')
ax.xaxis.set_major_formatter(matplotlib.ticker.FixedFormatter(ticklabels))
plt.show()

推荐阅读