Python JSON - 世界人口图,,世界人口图从http


世界人口图

从https://datahub.io/网站搜索population,下载世界人口json数据。

# world_population.pyimport jsonfrom country_codes import get_country_codeimport pygal_maps_world.maps as mapsfrom pygal.style import RotateStyle, LightColorizedStyle# 将数据加载到一个列表中filename = ‘data/population_data.json‘with open(filename) as f:    pop_data = json.load(f)# 创建一个包含人口数量的字典cc_populations = {}# 打印每个国家2016年的人口数量for pop_dict in pop_data:    for key in pop_dict:        if key == ‘Year_2016‘:            country = pop_dict[‘Country‘]            try:                population = int(pop_dict[key])            except:                pass            code = get_country_code(country)            if code:                print(code + ‘: ‘ + str(population))                cc_populations[code] = population            else:                print(‘ERROR - ‘ + country)# 根据人口数量将所有国家分成三组cc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}for cc, pop in cc_populations.items():    if pop < 10000000:        cc_pops_1[cc] = pop    elif pop < 1000000000:        cc_pops_2[cc] = pop    else:        cc_pops_3[cc] = pop# 看看每组分别包含多少个国家print(len(cc_pops_1), len(cc_pops_2), len(cc_pops_3))wm_style = RotateStyle(‘#336699‘, base_style=LightColorizedStyle)wm = maps.World(style=wm_style)wm.title = ‘World Population in 2016, by Country‘wm.add(‘0-10m‘, cc_pops_1)wm.add(‘10m-1bn‘, cc_pops_2)wm.add(‘>1bn‘, cc_pops_3)wm.render_to_file(‘world_population.svg‘)

技术图片

Python JSON - 世界人口图

评论关闭