# 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)
#sb.set_context('poster')


### 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()
m = Basemap(projection='gall',llcrnrlat=-70,urcrnrlat=90,\
llcrnrlon=-180,urcrnrlon=180,resolution='c')

#m.fillcontinents(color='tan')
m.drawmapboundary()

m.drawparallels(np.arange(-80.,81.,20.))
m.drawmeridians(np.arange(-180.,181.,20.))
#m.drawcoastlines()
#m.drawrivers(color='blue')

name='world',
drawbounds=True,
color='gray')

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

#end for

p = PatchCollection(patches, alpha=0.5,  zorder=3, cmap='rainbow')
p.set_array(np.array(population))

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

plt.title('World Choropleth')
plt.show()

In [ ]:


In [ ]: