1. 程式人生 > 實用技巧 >用Python畫世界地圖

用Python畫世界地圖

畫世界地圖

根據名字獲得國別碼

from pygal_maps_world.i18n import COUNTRIES


# 定義函式,返回適用於pygal的兩位國別碼
def get_country_code(country_name):
    # pygal兩位國別碼列表表示法:pygal.maps.world.COUNTRIES.items()
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
    return None

主函式

import json  # 匯入json模組
from pygal_maps_world.maps import World  # 匯入世界地圖
from pygal.style import RotateStyle, LightColorizedStyle  # 設定地圖的基色
from studyofpython.data_down.world_map.country_codes import get_country_code  # 匯入自己設定的獲取國別碼的函式

cc_population = {}  # 用來儲存從json檔案中寫入的字典
cc_pops_1 = {}  # 分組儲存按照人口
cc_pops_2 = {}
cc_pops_3 = {}
filename = "population_data.json"
with open(filename)as f:
    datas = json.load(f)
for data in datas:
    if data['Year'] == '2010':
        country_name = data['Country Name']
        population = int(float(data['Value']))
        code = get_country_code(country_name)
        if code:
            cc_population[code] = population
        else:
            print('ERROR-' + country_name)
for cc, pop in cc_population.items():
    if pop < 10000000:
        cc_pops_1[cc] = pop
    elif pop in range(10000000, 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 = World(style=wm_style)  # 建立地圖
wm.title = 'World Population in 2010,by Country'
wm.add('0-10m', cc_pops_1)  # 第一個是標籤,第二個是是一個包含    國別碼:人口數量   的字典
wm.add('10m-1bn', cc_pops_2)
wm.add('>10bn', cc_pops_3)
wm.render_to_file('world_population.svg')  # 儲存影象