python学习过程中的第一篇记录。
本文参考于《python编程:从入门到实践》。
文中的数据population_data.json可直接在网上找到。
import json
from pygal_maps_world.i18n import COUNTRIES
import pygal
from pygal.style import RotateStyle
def get_country_code(country_name):
"""从pygal获取两个字母的国别码"""
for icode, icountry in COUNTRIES.items():
if icountry == country_name:
return icode
# 如果没有此国家则返回none
return None
# 将数据加载到一个列表中
filename = 'population_data.json'
with open(filename) as f:
pop_data = json.load(f)
# 打印每个国家2010年的人口数量
# print(pop_data[0:2])
cc_populations = {}
for pop_dict in pop_data:
if pop_dict['Year'] == '2010':
country = pop_dict['Country Name']
population = int(float(pop_dict['Value']))
code = get_country_code(country)
if code:
cc_populations[code] = population
cc1, cc2, cc3 = {}, {}, {}
for code, pop in cc_populations.items():
if pop < 10000000:
cc1[code] = pop
elif pop < 1000000000:
cc2[code] = pop
else:
cc3[code] = pop
print(len(cc1), len(cc2), len(cc3))
def plot_map():
"""绘制交互式地图"""
style = RotateStyle('#336699')
wm = pygal.maps.world.World(style=style)
wm.title = 'World Population in 2010, by Country'
wm.add('0 - 10m', cc1)
wm.add('10m - 1bn', cc2)
wm.add('>1bn', cc3)
wm.render_to_file('world_population.svg')
if __name__ == "__main__":
plot_map()