每小时直方图-Matplotlib [英] Histogram per hour - matplotlib

查看:132
本文介绍了每小时直方图-Matplotlib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm analyzing public data on transport accidents in the UK.

我的数据框如下:

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

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

I'm trying to plot a histogram showing accident distribution by time of day, here is my code :

  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".我将如何去做?

In this graph, I'd like to change the labels on the x-axis to the format 'hh:mm'. How would I go about doing this?

推荐答案

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

What you are missing is setting the format of the matplotlib x-axis format:

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()

这篇关于每小时直方图-Matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆