用条形图绘制直方图
案例
在美国2004年人口普查发现有124 million的人在离家相对较远的地方工作.根据他们从家到上班地点所需要的时间,通过抽样统计(最后一列)出了下表的数据,这些数据怎么绘制成直方图:
| interval | width | quantity | quantity/width |
|---|---|---|---|
| 0 | 5 | 4180 | 836 |
| 5 | 5 | 13687 | 2737 |
| 10 | 5 | 18618 | 3723 |
| 15 | 5 | 19634 | 3926 |
| 20 | 5 | 17981 | 3596 |
| 25 | 5 | 7190 | 1438 |
| 30 | 5 | 16369 | 3273 |
| 35 | 5 | 3212 | 642 |
| 40 | 5 | 4122 | 824 |
| 45 | 15 | 9200 | 613 |
| 60 | 30 | 6461 | 215 |
| 90 | 60 | 3435 | 57 |
这些数据是无法直接使用hist来绘制直方图的,但是可以通过条形图改造绘制成直方图
from matplotlib import pyplot as plt
from matplotlib import font_manager
my_font = font_manager.FontProperties(fname='/usr/share/fonts/cjkuni-uming/uming.ttc')
interval = [0,5,10,15,20,25,30,35,40,45,60,90]
width = [5,5,5,5,5,5,5,5,5,15,30,60]
quantity = [836,2737,3723,3926,3596,1438,3273,642,824,613,215,57]
plt.figure(figsize=(20, 8), dpi=80)
plt.bar(range(len(quantity)), quantity, width=1) # width=1 表示之间没有空隙,默认为0.8
_x = [i-0.5 for i in range(13)] # 设置起点在方格的左侧
_xtick_labels = interval+[150] # 最后一个间距是60,到150,将150添加到列表中
plt.xticks(_x, _xtick_labels)
plt.grid()
plt.show()

332

被折叠的 条评论
为什么被折叠?



