Last active
January 24, 2018 13:39
-
-
Save jaklinger/9d1acae50be39f7577af11a7de24f0a7 to your computer and use it in GitHub Desktop.
Example of drawing choropleth using Matplotlib Basemap with Natural Earth boundary data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Uncomment this for notebooks | |
# %matplotlib inline | |
import matplotlib as mpl | |
from matplotlib.patches import Polygon | |
from matplotlib.collections import PatchCollection | |
from mpl_toolkits.basemap import Basemap | |
import numpy as np | |
# Country codes --> alpha | |
data = {"AU":0.2,'GB':0.6,'US':0.8} | |
# Set up the figure | |
fig,ax = plt.subplots(figsize=(22, 12)) | |
m = Basemap(lon_0=0, projection='robin') | |
m.drawmapboundary(color='w') | |
# You can find this file here: | |
# http://www.naturalearthdata.com/downloads/10m-cultural-vectors/10m-admin-0-countries/ | |
# Read the shapefile data | |
m.readshapefile('countries/natural-earth-10m/ne_10m_admin_0_countries_lakes', | |
'units', color='#444444', linewidth=.2) | |
# Fill countries in 'data' as red with appropriate alpha | |
# Otherwise fill countries as blue with random alpha | |
for info, shape in zip(m.units_info, m.units): | |
# Get the country code, and assign colour and alpha | |
country_code = info['ISO_A2'] | |
color = 'blue' | |
alpha = np.random.random() | |
if country_code in data: | |
color = 'red' | |
alpha = data[country_code] | |
# Setup and add country patches | |
patches = [Polygon(np.array(shape), True)] | |
pc = PatchCollection(patches) | |
pc.set_facecolor(color) | |
pc.set_alpha(alpha) | |
ax.add_collection(pc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment