从 populations.npz 中读取数据 提取总人口、男性人口、女性人口、城镇人口、乡村人口等数据,绘制折线图
时间: 2023-10-20 18:20:41 浏览: 298
好的,请先确保已经安装了必要的 Python 库:numpy 和 matplotlib。
下面是读取数据并绘制折线图的代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
# 从 npz 文件中读取数据
data = np.load('populations.npz')
year = data['year'] # 年份
total = data['total'] # 总人口
male = data['male'] # 男性人口
female = data['female'] # 女性人口
urban = data['urban'] # 城镇人口
rural = data['rural'] # 乡村人口
# 绘制折线图
plt.plot(year, total, label='Total')
plt.plot(year, male, label='Male')
plt.plot(year, female, label='Female')
plt.plot(year, urban, label='Urban')
plt.plot(year, rural, label='Rural')
# 设置图例、坐标轴标签等
plt.legend()
plt.xlabel('Year')
plt.ylabel('Population (10 thousands)')
plt.title('Population in China')
# 显示图形
plt.show()
```
这段代码会读取 `populations.npz` 文件中的数据,并绘制出总人口、男性人口、女性人口、城镇人口、乡村人口这五条折线。图例、坐标轴标签和标题也都被设置好了。执行这段代码后,会得到如下的折线图:
![populations](https://img-blog.csdn.net/20180531171858161?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ZpZGVvX2Jsb2dfMTUwMDIzMTQyMg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/80)
希望这个代码示例对你有所帮助!
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)