首页 > 解决方案 > 使用带有手动 bin 的 Python 绘制直方图

问题描述

我正在尝试使用 matplotlib.hist() 函数绘制直方图。

有人可以帮我得到正确的直方图吗?

import matplotlib.pyplot as plt

list_age = ['26','28','26','36','38','31','22','31','25','30','37','27','27','29','27','21','27','38','31','41','28','31','28','33','26','39','37','24','31','34','39','33','22', '30','24','29','28','34','27','28','26','26','25','40','24','37','24','28','26','29','26','31','23','31','36','32','25','31','25','33','36','27','28',
'25','27','39','36','30','31','34','23','31','32','31','33','32','39','35','35','22','34','25','35','35','41','20','21','35','32','30','22','21','23','33','25','30','24','39','24','27','22','33','30','27','30','23','29','30','22','31','29','31','24','29','25','24','26','29','31','24','32','21','25','29','30']

list_age.sort()

bins = 55

plt.hist(list_age, bins, facecolor='g')

plt.xlabel('Years')

plt.ylabel('Probability')

plt.grid(True)

plt.show()

标签: pythonpython-3.xmatplotlib

解决方案


您需要先将 list_age转换为整数列表(而不是字符串列表)。然后,只需使用选项density(或normed)来显示概率,并使用 xticks来更改 x 轴的刻度。

import matplotlib.pyplot as plt

list_age = ['26','28','26','36','38','31','22','31','25','30','37','27','27','29','27','21','27','38','31','41','28','31','28','33','26','39','37','24','31','34','39','33','22', '30','24','29','28','34','27','28','26','26','25','40','24','37','24','28','26','29','26','31','23','31','36','32','25','31','25','33','36','27','28',
'25','27','39','36','30','31','34','23','31','32','31','33','32','39','35','35','22','34','25','35','35','41','20','21','35','32','30','22','21','23','33','25','30','24','39','24','27','22','33','30','27','30','23','29','30','22','31','29','31','24','29','25','24','26','29','31','24','32','21','25','29','30']
list_age = [ int(i) for i in list_age ]

bins = len(set(list_age))
plt.hist(list_age, bins = bins, density = True, facecolor = "g")    # Replace density by normed if older version of matplotlib
plt.xticks(range(0, 55, 5))
plt.xlabel('Years')
plt.ylabel('Probability')
plt.grid(True)
plt.show()

如果要在特定箱中显示条形图,只需在其坐标处定义箱:

plt.hist(list_age, bins = [ 0, 20, 25, 30, 35, 40, 45, 50, 55 ], density = True, facecolor = "g")

推荐阅读