Python 绘制男女人口数目直方图 - 代码示例
以下是 Python 绘制男女人口数目的直方图代码:
import matplotlib.pyplot as plt
import numpy as np
# 数据
men = [45, 50, 60, 80, 100]
women = [40, 55, 70, 90, 110]
# 直方图
ind = np.arange(len(men))
width = 0.35
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men, width, color='blue', label='Men')
rects2 = ax.bar(ind + width/2, women, width, color='pink', label='Women')
# 添加标签、标题和网格线
ax.set_xticks(ind)
ax.set_xticklabels(('0-19', '20-39', '40-59', '60-79', '80+'))
ax.set_ylabel('Population')
ax.set_title('Population by Age and Gender')
ax.legend()
ax.grid()
# 显示图形
plt.show()
这段代码使用了 Matplotlib 库中的 pyplot 模块来绘制直方图。首先,我们定义了男性和女性的人口数据,然后使用 numpy 库中的 arange 函数生成了 x 轴的坐标。接着,我们使用 bar 函数绘制了两组直方图,并使用 set_xticklabels 函数设置了 x 轴的标签。最后,我们添加了标题、标签和网格线,并使用 show 函数显示图形。
原文地址: https://www.cveoy.top/t/topic/nC29 著作权归作者所有。请勿转载和采集!