python pygal绘制世界人口地图
- 首先打开json文件
fileName = "population_data.json" with open(fileName) as f: pop_data = json.load(f) # json.load()将数据转化为python能够处理的格式,这里是一个列表。
- python不能将包含小数点的字符串‘1232432.324’转换为整数,应该先将字符串转换为浮点数,再将浮点数转换为整数
population = int(float(pop_dict['Value']))
- 标准化国别码集
from pygal_maps_world.i18n import COUNTRIES
def get_country_code(country_name): for code, name in COUNTRIES.items(): if name == country_name: return code return None - 制作世界地图
wm_style = pygal.style.RotateStyle('#3399AA', base_style=pygal.style.LightColorizedStyle) wm = pygal.maps.world.World(style=wm_style) - 所有完整源码:
import json import pygal from pygal_maps_world.i18n import COUNTRIES import pygal.maps.world def get_country_code(country_name): for code, name in COUNTRIES.items(): if name == country_name: return code return None fileName = "population_data.json" with open(fileName) as f: pop_data = json.load(f) # json.load()将数据转化为python能够处理的格式,这里是一个列表 cc_populations = {} for pop_dict in pop_data: if pop_dict['Year'] == '2010': country_name = pop_dict["Country Name"] population = int(float(pop_dict['Value'])) code = get_country_code(country_name) if code: cc_populations[code] = population else: print('ERROR - ' + country_name) # print(country_name + ':' + str(population)) cc_pop1, cc_pop2, cc_pop3 = {}, {}, {} for cc,pop in cc_populations.items(): if pop < 10000000: cc_pop1[cc] = pop elif pop < 1000000000: cc_pop2[cc] = pop else: cc_pop3[cc] = pop print(len(cc_pop1), len(cc_pop2), len(cc_pop3)) # 画图 # wm_style是一个样式对象,第一个实参表示颜色,十六进制格式,分别表示红绿蓝的分量(RGB),第二个实参表示加亮颜色主题 wm_style = pygal.style.RotateStyle('#3399AA', base_style=pygal.style.LightColorizedStyle) wm = pygal.maps.world.World(style=wm_style) wm.title = "World Population in 2010,by Country" # add接收一个标签和一个列表,此例中标签为人口数量区间,列表是国家和人口数量的列表 wm.add('0-10m', cc_pop1) wm.add('10-1bn', cc_pop2) wm.add('>1bn', cc_pop3) wm.render_to_file('world_population.svg') - 运行效果:
Dana.Lee
To:Dana_Lee1016@126.com
浙公网安备 33010602011771号