Histogram per hour - matplotlib

依然范特西╮ 提交于 2019-12-08 06:03:52

问题


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

My dataframe looks like this :

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

This is the output:

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?


回答1:


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


来源:https://stackoverflow.com/questions/53244590/histogram-per-hour-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!