最近在看<python從入門到實踐>,其中有一個例子是使用pygal制作世界人口地圖,覺得挺有意思的,這里就記錄下來了, 其實代碼不是很復雜,使用環境環境python3.廢話不多說,直接上代碼
country_codes.py
返回當前國家的國別碼
需要安裝pygal_maps_world
pip install pygal_maps_world
# *- coding: utf-8 -*- from pygal_maps_world.i18n import COUNTRIES def get_country_code(country_name): for code, name in COUNTRIES.items(): if name == country_name: return code return None if __name__ == '__main__': print(get_country_code('China'))
world_pople.py
需要安裝pygal
pip install pygal
# *- coding: utf-8 -*- import json from country_codes import get_country_code import pygal_maps_world.maps as pm from pygal.style import RotateStyle with open('population_data.json') as f: data = json.load(f) cc_populations = {} for line in data: if line['Year'] == '2010': #查找年分為2010年的 country_name = line['Country Name'] population = int(float(line["Value"])) code = get_country_code(country_name) if code: cc_populations[code] = population #將國家按不同范圍進行分組 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 < 100000000: cc_pops_2[cc] = pop else: cc_pops_3[cc] = pop #初始化一個world對象 wm = pm.World() #設置分組顏色 wm_style = RotateStyle('#336699') wm.title = 'World Population in 2010, 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_populations.svg')
效果圖
結尾
可以看到圖片中有許多地方是沒有顏色填充,這個是因為在傳入國家名稱的時候在 from pygal_maps_world.i18n import COUNTRIES 無法找到當前國家的國別碼,所以就沒有將當前國家添加到cc_populations中.
后續這個地方會完善的.
附件:https://files-cdn.cnblogs.com/files/charles1ee/population_data.json.tar.gz