大家好,我是执念斩长河,一个刚刚学习python绘图的学渣。今天非常开心阅读了《python数据可视化》(黑马程序员编著)其中的“绘制人口金字塔图”章节被我成功运行出来,特此写篇博文纪念自己。
人口金字塔图用来描述人口年龄与性别分布状况的图形,用来表现人口的现状及其发展类型。人口金字塔图一般以年龄为纵轴、人口数为横轴,按年龄自然顺序自下而上在纵轴左侧和右侧绘制并列的横向矩形条,纵轴左侧为男,右侧为女。
请绘制以下的图形
根据图片可以了解到人口金字塔左侧的一组矩形代表各年龄段男性的人口数,右侧的一组矩形代表各年龄段女性人口数.pyplot可以使用barh()函数绘制人口金字塔图.
用到的数据
AgeGroup Gender Number
0-9 Male -70812
10-19 Male -64963
20-29 Male -89947
30-39 Male -86653
40-49 Male -98391
50-59 Male -79226
60-69 Male -59308
70-79 Male -26564
80-89 Male -9418
90+ Male -791
0-9 Female 60814
10-19 Female 55015
20-29 Female 83940
30-39 Female 84858
40-49 Female 94789
50-59 Female 77357
60-69 Female 60288
70-79 Female 28578
80-89 Female 11897
90+ Female 1628
将其保存到“population.xlsx”文件里
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
df = pd.read_excel(r'population.xlsx')
df_male = df.groupby(by='Gender').get_group('Male')
list_male = df_male['Number'].values.tolist()
df_female = df.groupby(by = 'Gender').get_group('Female')
list_female = df_female['Number'].values.tolist()
df_age = df.groupby('AgeGroup').sum()
count = df_age.shape[0]
y = np.arange(1,11)
labels = []
for i in range(count):
age = df_age.index[i]
labels.append(age)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.barh(y,list_male,tick_label=labels,label='男',color='#6699FF')
ax.barh(y,list_female,tick_label=labels,label='女',color='#CC6699')
ax.set_ylabel('年龄段(岁)')
ax.set_xticks([-100000,-75000,-50000,-25000,
0,25000,50000,75000,100000])
ax.set_xticklabels(['100000','75000','50000','25000','0','25000','50000','75000','100000'])
ax.set_xlabel('人数')
ax.set_title('某城市人口金字塔')
ax.legend()
plt.show()
这种代码方便收藏,用到的时候,在自己空间里进行搜索,直接调试运行即可。
import seaborn as sns
import matplotlib.pyplot as plt
data = {'M': [3.18,3,2.88,2.8,3.36,4.49,3.39,3.66,3.91,4.69,4.28,2.56,2.97,2.21,1.38,0.94,0.58,0.24,0.06,0.01],
'F': [...
import numpy as np
#,encoding='ISO-8859-1'
df = pd.read_csv(r"F:\China-2019.csv",header=0)
plt.rcParams['font.sans-serif'] = ['S
设置数据库
docker pull postgres
docker run --name postgres -e POSTGRES_PASSWORD=placeholder -d postgres
运行机器人的选项
如果通过pipenv运行(用于开发),则必须在pipenv run start之前pipenv run start docker-compose up postgres 。
如果仅使用docker,则可以使用docker-compose up设置整个机器人。