世界人口图
从https://datahub.io/网站搜索population,下载世界人口json数据。
from pygal.maps.world import COUNTRIES def get_country_code(country_name): """根据指定的国家,返回pygal使用的两个字母的国别码""" for code, name in COUNTRIES.items(): if name == country_name: return code # 如果没有找到指定的国家,就返回None return None if __name__ == '__main__': print(get_country_code('Andorra')) print(get_country_code('United Arab Emirates')) print(get_country_code('Afghanistan'))
# world_population.py import json from country_codes import get_country_code import pygal_maps_world.maps as maps from 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')