1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
def plot_age_pyramid(df, year): year_data = df[df['year'] == year].iloc[0]
age_groups = ['0-14', '15-64', '65+'] male_pop = [year_data['male_0_14'], year_data['male_15_64'], year_data['male_65+']] female_pop = [year_data['female_0_14'], year_data['female_15_64'], year_data['female_65+']]
fig, ax = plt.subplots(figsize=(10, 8)) y_pos = np.arange(len(age_groups))
ax.barh(y_pos, male_pop, align='center', label='男性', color='blue') ax.barh(y_pos, [-x for x in female_pop], align='center', label='女性', color='red') ax.set_yticks(y_pos) ax.set_yticklabels(age_groups) ax.set_xlabel('人口数量') ax.set_title(f'{year}年人口年龄结构') ax.legend() plt.show()
plot_age_pyramid(df, 2020)
|