Skip to main content
 首页 » 编程设计

python之使用带有手动分箱的 Python 绘制直方图

2024年12月31日13grandyang

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

  • 下面的代码没有得到正确的直方图
  • X轴是年数(年龄),X轴我要0 20,25,30,35,40,45,50,55
  • Y轴是概率

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

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

请您参考如下方法:

您需要先将您的 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() 

如果您想在特定的 bin 处显示条形图,只需在其坐标处定义 bin:

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