每小时直方图

问题描述 投票:0回答:1

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

我的数据框看起来像这样:

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”。我该怎么做呢?

python matplotlib group-by histogram
1个回答
4
投票

您缺少的是设置 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()
© www.soinside.com 2019 - 2024. All rights reserved.