Nav apraksta

world_population.py 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import json
  2. from pygal.maps.world import World
  3. from pygal.style import LightColorizedStyle as LCS, RotateStyle as RS
  4. from country_codes import get_country_code
  5. # Load the data into a list.
  6. filename = 'population_data.json'
  7. with open(filename) as f:
  8. pop_data = json.load(f)
  9. # Build a dictionary of population data.
  10. cc_populations = {}
  11. for pop_dict in pop_data:
  12. if pop_dict['Year'] == '2010':
  13. country_name = pop_dict['Country Name']
  14. population = int(float(pop_dict['Value']))
  15. code = get_country_code(country_name)
  16. if code:
  17. cc_populations[code] = population
  18. # Group the countries into 3 population levels.
  19. cc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}
  20. for cc, pop in cc_populations.items():
  21. if pop < 10000000:
  22. cc_pops_1[cc] = pop
  23. elif pop < 1000000000:
  24. cc_pops_2[cc] = pop
  25. else:
  26. cc_pops_3[cc] = pop
  27. # See how many countries are in each level.
  28. print(len(cc_pops_1), len(cc_pops_2), len(cc_pops_3))
  29. wm_style = RS('#336699', base_style=LCS)
  30. wm = World(style=wm_style)
  31. wm.force_uri_protocol = 'http'
  32. wm.title = 'World Population in 2010, by Country'
  33. wm.add('0-10m', cc_pops_1)
  34. wm.add('10m-1bn', cc_pops_2)
  35. wm.add('>1bn', cc_pops_3)
  36. wm.render_to_file('world_population.svg')