python - 每小时直方图 - 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”。我该怎么做呢?
解决方案
您缺少的是设置 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()
推荐阅读
- algorithm - 如何从背包问题的 DP 表中导出最大数量的项目?
- amazon-web-services - 无法运行 gitlab autodevops
- android - 有没有办法在 TextInputLayout 中使用背景作为提示?
- java - Java Oauth request_token 流示例,没有库
- python - Python Folium Choropleth Map - 图例编号重叠
- python - 为什么 Folium 渲染颜色为单一颜色?
- assembly - 以编程方式调用外部程序存储器函数
- spring - Spring - 多个@ControllerAdvice 导致 BeanCurrentlyInCreationException
- xaml - 如何从 TextBox 标记向 ResourceDictionary 中找到的 TextBlock 标记的 Text 属性传递一个值
- python - 在 CVXPy 中使用逻辑函数时溢出