Global Choropleth Example

We use shapefiles from the Natural Earth website, that have been previously downloaded

Set up imports; because we will be handling shapefiles, we need polygon helper functions

In [1]:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

# these are needed for shapefile mgt 
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from matplotlib.patches import PathPatch
#import seaborn as sb

Different way of setting figure size (do it once for whole notebook)

In [2]:
#from pylab import rcParams
import pylab

%matplotlib inline
pylab.rcParams['figure.figsize'] = (16,8)

module design flow:

  • Create a figure
  • Create a global map from Basemap; we use a projection that is rectangular, and not too size distorting
  • Draw the map boundry, and the line of lat and lon (note the fillcontinents call is commented out, as we will be filling countries with a color derived from their population)
  • Read the shapefile, specifying the name world for subsequent reference
  • For all polygons in the shapefile, use numpy to turn them into an array, then into a Patch, then add to collection of patches
  • for each patch added, get the Estimated Population attribute, take log10 (safetly), and add that to a list of population values
  • Build a PatchCollection from the list of patches; this is where we set graphical attributes like the color map we want, the degree of tranparency, and the order of drawing (make it high to see it)
  • See the attribute for each patch that is used to look up the color map (by set_array()
  • Add the patch collection to the current axes object
  • Create a color bar, and manually set the tick marks (1-10), and the tick mark labels (1-1,000,000,000)
In [3]:
fig = plt.figure()
ax = fig.add_subplot(111)
m = Basemap(projection='gall',llcrnrlat=-70,urcrnrlat=90,\




import math   
import numbers
patches = []
population  = []
for info,shape in zip(m.world_info,
    patches.append(Polygon(np.array(shape), True))
    if( isinstance(info['POP_EST'], numbers.Number)  ):
            z = math.log10(info['POP_EST']+1.0)
            z = 0
        #end try
        z = 0.0
    #end if
#end for

p = PatchCollection(patches, alpha=0.5,  zorder=3, cmap='rainbow')

cb = fig.colorbar(p, ax=ax, shrink=0.6, ticks = range(0,10))
tick_labels = ["{:,}".format(10**i) for i in range(0,10)]'Country Population', size = 8)

plt.title('World Choropleth')
In [ ]:
In [ ]: