jupyternotebook如何画人口金字塔图
时间: 2023-09-24 10:08:06
浏览: 121
可以使用Python的matplotlib库来画人口金字塔图。如下示例代码:
```python
import matplotlib.pyplot as plt
age_groups = ['0-4', '5-9', '10-14', '15-19', '20-24',
'25-29', '30-34', '35-39', '40-44', '45-49',
'50-54', '55-59', '60-64', '65-69', '70-74',
'75-79', '80-84', '85-89', '90-94', '95-99', '100+']
male_population = [9845, 10170, 10487, 10956, 11749, 13053,
13398, 12887, 11714, 9922, 8002, 6142,
4381, 2799, 1701, 928, 368, 86, 10, 1, 0]
female_population = [9385, 9749, 10157, 10714, 11520, 12943,
13327, 12983, 11848, 10220, 8380, 6494,
4561, 2998, 1835, 1025, 428, 107, 13, 1, 0]
fig, axs = plt.subplots(figsize=(8, 10), sharex=True, gridspec_kw={'hspace': 0})
# Male population pyramid
axs.barh(age_groups, male_population, align='center', color='blue', label='Male')
axs.barh(age_groups, [-x for x in female_population], align='center', color='pink', label='Female')
axs.set_xlim(-16000, 16000)
axs.set_xlabel('Population')
axs.set_ylabel('Age group')
axs.set_title('Population Pyramid')
axs.legend()
plt.show()
其中,`age_groups` 是年龄组列表,`male_population` 是男性人口数量列表,`female_population` 是女性人口数量列表。通过 `barh` 函数画出柱状图,设置颜色和标签,最后通过 `legend` 函数添加图例。
执行代码后,会生成如下图所示的人口金字塔图:
![image.png](https://cdn.nlark.com/yuque/0/2021/png/263975/1613354243195-c9adf153-d5ee-4065-8e0c-3588a31f6017.png#align=left&display=inline&height=438&name=image.png&originHeight=438&originWidth=573&size=27010&status=done&style=none&width=573)