我正在尝试使用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()
答案 0 :(得分:1)
您需要先将 list_age 转换为整数列表(而不是字符串列表)。 然后,只需使用选项密度(或标准)来显示概率,使用 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")