python.json/pygal.maps.world学习范例-读取json格式文件、生成世界地图

import pygal
import json
#国别码存储的模块2位
from pygal.maps.world import COUNTRIES
#修改图表的主题(背景色、标签、颜色)
from pygal.style import LightColorizedStyle as LCS,RotateStyle as RS


#文件国别码为三字母,定义函数,根据指定的国家返回pygal使用的两个字母的国别码
def get_country_code(country_name):
for code,name in COUNTRIES.items():
if name==country_name:
return code
return None


#将数据加载到列表
filename='D:\python program\population_data.json'
with open(filename) as f:
pop_data=json.load(f)


#创建一个包含人口数量的字典,国别码和人数
cc_populations={}
for pop_dict in pop_data:
if pop_dict['Year']=='2010-09-29':
country_name=pop_dict['Country Name']
population=int(pop_dict['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 < 1000000000:
cc_pops_2[cc]=pop
else:
cc_pops_3[cc]=pop


#制作地图
wm=pygal.maps.world.World()   #创建一个实例
wm.title='2010年世界人口分布图'
wm.add('0-10m',cc_pops_1)  #add()接受几个标签和列表
wm.add('10m-1bn',cc_pops_2)
wm.add('>1bn',cc_pops_3)
wm_style=RS('#336699',base_style=LCS)  #加亮颜色主题

wm.render_to_file('世界人口分布图.svg')


猜你喜欢

转载自blog.csdn.net/choven_meng/article/details/78148456