python - 使用带有手动 bin 的 Python 绘制直方图
问题描述
我正在尝试使用 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()
如果要在特定箱中显示条形图,只需在其坐标处定义箱:
plt.hist(list_age, bins = [ 0, 20, 25, 30, 35, 40, 45, 50, 55 ], density = True, facecolor = "g")
推荐阅读
- azure - 图形数据科学库不在 Azure Neo4j VM 中
- symfony - Symfony 5 Stripe Webhook 重定向 307
- javascript - Google App 脚本 - 映射时出错 - TypeError:无法读取未定义的属性“地图”
- .net - 如何在 .Net v 4 项目中安装 Dataflow 库?
- sql - SQL:如何在另一列中按 MAX 提取一行,在另一个列序列中提取 DISTINCT?
- sql-server - 取一个字段的总和,并按年龄等其他数字字段自动将其分组。试图找到一种更简单的方法来编写以下查询
- typescript - 如何检查通用对象上是否存在通用属性
打字稿 - ios - 如果在手机关闭时发送 iPhone Pass 推送通知,则不会收到
- scala - Spark - StringIndexer 与 OneHotEncoderEstimator
- javascript - Firebase 按字段排序集合