1. 导入 numpy 和 matplotlib 库,并读取数据文件并命名为 data:
import numpy as np
import matplotlib.pyplot as plt

data = np.load('chapter3 populations.npz')
  1. 分别定义变量保存 data 中的数组,并输出:
year = data['year']
population = data['population']
male = data['male']
female = data['female']
urban = data['urban']
rural = data['rural']

print(year)
print(population)
print(male)
print(female)
print(urban)
print(rural)
  1. 定义画布大小 figsize=(15,5),创建 1 行 2 列的子图,并绘制散点图:
fig, axes = plt.subplots(1, 2, figsize=(15, 5))

axes[0].scatter(year, male, label='Male')
axes[0].scatter(year, female, label='Female')
axes[0].set_xlabel('Year')
axes[0].set_ylabel('Population')
axes[0].set_title('Population Change by Gender')
axes[0].legend()

axes[1].scatter(year, urban, label='Urban')
axes[1].scatter(year, rural, label='Rural')
axes[1].set_xlabel('Year')
axes[1].set_ylabel('Population')
axes[1].set_title('Population Change by Location')
axes[1].legend()

plt.show()
  1. 绘制出 1996 年和 2015 年的男女人口比例及城乡人口比例饼图,并将图像保存到桌面:
labels = ['Male', 'Female']
sizes_1996 = [male[0], female[0]]
sizes_2015 = [male[-1], female[-1]]

fig, axes = plt.subplots(1, 2, figsize=(10, 5))

axes[0].pie(sizes_1996, labels=labels, autopct='%1.1f%%')
axes[0].set_title('Gender Population Ratio in 1996')

axes[1].pie(sizes_2015, labels=labels, autopct='%1.1f%%')
axes[1].set_title('Gender Population Ratio in 2015')

plt.savefig('C:/Users/Username/Desktop/population_ratio.png')
plt.show()

labels = ['Urban', 'Rural']
sizes_1996 = [urban[0], rural[0]]
sizes_2015 = [urban[-1], rural[-1]]

fig, axes = plt.subplots(1, 2, figsize=(10, 5))

axes[0].pie(sizes_1996, labels=labels, autopct='%1.1f%%')
axes[0].set_title('Location Population Ratio in 1996')

axes[1].pie(sizes_2015, labels=labels, autopct='%1.1f%%')
axes[1].set_title('Location Population Ratio in 2015')

plt.savefig('C:/Users/Username/Desktop/location_ratio.png')
plt.show()

请注意将 'C:/Users/Username/Desktop/' 替换为您计算机上实际的桌面路径。


原文地址: https://www.cveoy.top/t/topic/pldt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录