1.获取两个字的国别码
#先安装pygal_maps_world
from pygal_maps_world.i18n import COUNTRIES #导入COUNTRIES字典 包含健和值为国别码和国家名
def get_country_code(country_name):
for code,name in COUNTRIES.items():
if name == country_name:
return code
return None
print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates'))
print(get_country_code('Afghanistan'))
运行结果
ad
ae
af
2.创建北美 中部 南美的简单地图
import pygal
#wm=pygal_maps_world.Worldmap()
wm = pygal.maps.world.World()#创建实例
wm.title="北美,中部,南美"#标题
wm.add("北美",['ca','mx','us'])#为指定的国家选择一种颜色,第一个参数是标签,在图表左边显示该颜色和指定的标签
wm.add("中部",['bz','cr','gt','hn','ni','pa','sv'])
wm.add("南美",['ar','bo','br','cl','co','ec','gf',
'gy','pe','py','sr','uy','ve'])
wm.render_to_file("americas.svg")
3.在世界地图上呈现数字数据
import pygal
wm=pygal.maps.world.World()
wm.title="北美的人口数量"
wm.add("北美",{"ca":34126000,"us":309349000,"mx":113423000}) #标签是北美,第二个参数传了一个字典,国别码作为键,人口数作为值,
# pygal自动根据这些数字给不同国家不同颜色,人口数量越多颜色越深
wm.render_to_file("na_population.svg")
4.制作世界人口地图
import json
import pygal
from pygal.style import RotateStyle as RS ,LightColorizedStyle as LCS #调整基色和亮度
from country_code import get_country_code
#将数据加载到一个列表中
filename="population_data.json"
with open(filename) as f:
pop_data=json.load(f) #将数据转化为python可以处理的个格式,此处为列表
#创建一个包含人口数量的字典
cc_populations={}
#打印每个国家2010年的人口数数量
for pop_dict in pop_data:
if pop_dict["Year"] == "2010": #键年等于2010
country_name = pop_dict["Country Name"] #将键Country Name对应的值传给country_name
population = int(float(pop_dict["Value"]))#int不可以直接处理带小数的数据
#print(country_name + ":" + str(population))#打印人口数量时需要将数字转化为字符
code=get_country_code(country_name)
if code:
cc_populations[code] = population
#根据人口数量将所有的国家分成三组 <1000w,<10yi,>10yi
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
elif pop<10000000000:
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) #创建样式实例 传递一个十六进制RGB颜色,
# 混合少点红色33,多一点绿色66,更多蓝色99
#将LightColorizedStyle作为基本样式
wm=pygal.maps.world.World(style = wm_style) #将样式存储在style中 利用关键字参数传递给wm
wm.title="2010年各国人口数量"
wm.add('0-10m',cc_pops_1)#标签,字典
wm.add('10m-1bm',cc_pops_2)
wm.add('>1bm',cc_pops_3)
wm.render_to_file("world_population.svg")