数据分析世界地图
作者:互联网
import pygal
import json
import pygal.maps.world
from pygal.style import LightColorizedStyle as LCS, RotateStyle as RS
filename = ‘population_data.json’
with open(filename) as f:
pop_data = json.load(f)
def get_country_code(country_name):
“”“根据指定的国家返回pygal的国别码”""
for co, name in pygal.maps.world.COUNTRIES.items():
if name == country_name:
return co
# 如果没有找到国家返回none
return None
创建一个包含人口数据的字典
cc_populations = {}
for pop_dict in pop_data:
if pop_dict[‘Year’] == ‘2010’:
country_name = pop_dict[‘Country Name’]
# float将字符串转换为小数,int丢弃小数部分
population = int(float(pop_dict[‘Value’]))
co = get_country_code(country_name)
if co:
cc_populations[co] = population
print(cc_populations)
根据人口数量将所有国家分为三个组
cc_pops1, cc_pos2, cc_pos3 = {}, {}, {}
for cc, pop in cc_populations.items():
if pop < 10000000:
cc_pops1[cc] = pop
elif pop < 1000000000:
cc_pos2[cc] = pop
else:
cc_pos3[cc] = pop
查看每组分别包含多少个国家
print(len(cc_pops1), len(cc_pos2), len(cc_pos3))
wm_style = RS(’#336699’, base_style=LCS)
wm = pygal.maps.world.World(style=wm_style)
wm.title = “populations of countries in north amercia”
wm.add(‘0-10m’, cc_pops1)
wm.add(‘10m-1bn’, cc_pos2)
wm.add(’>10bn’, cc_pos3)
wm.render_to_file(‘na_population.svg’)
标签:数据分析,name,cc,country,wm,pop,世界地图,pygal 来源: https://blog.csdn.net/qq_38501057/article/details/88427335