Python 绘制2016世界GDP地图

2016世界GDP地图

从https://datahub.io/core/gdp#data下载得到json文件。

# country_code.py 获取国家二字代码

# 从pygal.maps.world模块导入{国家代码:国家名字}的列表
from pygal.maps.world import COUNTRIES 

import json

# 创建找国家代码的函数
def get_country_code(country):
    for code, name in COUNTRIES.items():
        if name == country:
            return code

    return None


if __name__ == '__main__':
    filename = 'world_GDP.json'
    with open(filename) as f:
        data = json.load(f)
    
    for dic in data:
        for key in dic:
            if key == 'Year':
                if dic[key] == 2016:
                    country = dic['Country Name']
                    print(country + ': ', get_country_code(country))
# world_GDP.py 世界2016年GDP

# 导入json模块
import json

# 从country_code.py文件导入get_country_code函数
from country_code import get_country_code

# 将pygal_maps_world.maps模块导入并命名为maps
import pygal_maps_world.maps as maps

# 导入数据
filename = 'world_GDP.json'
with open(filename) as f:
    data = json.load(f)

# 世界GDP字典
cc_gdp = {}

# 解析数据
for dic in data:
    # 遍历所有在data中的字典

    for key in dic:
        # 遍历字典的键

        if key == 'Year':
            # 如果键是'Year'

            if dic[key] == 2016:
                # 如果字典的Year键的值为2016

                country = dic['Country Name']
                value = dic['Value']
                code = get_country_code(country)
                if code:
                    cc_gdp[code] = value
                else:
                    pass

# 创建世界地图并设置标题以及标签数据
wm = maps.World()
wm.title = 'World GDP in 2016, by country'
wm.add('2016', cc_gdp)

# 渲染地图,保存为
wm.render_to_file('world_gdp.svg')

# 保存文件可以使用浏览器查看

猜你喜欢

转载自www.cnblogs.com/noonjuan/p/10847125.html