主程序:
# -*- coding: utf-8 -*-"""Created on Sun Oct 22 19:57:24 2017@author: dqhpl"""import jsonimport pygal.maps.worldfrom country_codes import get_country_codefrom pygal.style import RotateStyle as RS, LightColorizedStyle as LCS #利用as创建简写,便于书写#将数据加载到一个列表之中filename = 'population_data.json'with open(filename) as f: pop_data = json.load(f)#创建一个包含人口数量的字典cc_populations = {}#打印每个国家2015年的人口数量for pop_dict in pop_data: if pop_dict['Year'] =='2010': country = pop_dict['Country Name'] population= int(float(pop_dict['Value']))#由于直接转int会出错。所以先转float再转int #print(country_name + ": " + str(population)) code= get_country_code(country) if code: cc_populations = 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 <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 = RS('#336699', base_style=LCS)#创建了一种基调,LCS指的是用亮色风格wm = pygal.maps.world.World(style= wm_style)#pygal升级,所以需要注意 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')
country_codes.py
# -*- coding: utf-8 -*-"""Created on Sun Oct 22 20:09:53 2017@author: dqhpl"""# =============================================================================# The i18n module was removed in pygal-2.0.0, #however, it can now be found in the pygal_maps_world plugin.# # You can install that with pip install pygal_maps_world. #Then you can access COUNTRIES as pygal.maps.world.COUNTRIES:# # from pygal.maps.world import COUNTRIES# Whats left of the i18n module can be imported with:# # from pygal_maps_world import i18n# =============================================================================from pygal_maps_world import i18nfrom pygal.maps.world import COUNTRIESdef get_country_code(country_name): """根据指定的国家,返回pygal使用的两个字母的国别码""" for code, name in COUNTRIES.items(): if name == country_name: return code #如果没有找到指定的国家,就返回None return None