#!/usr/bin/env python # coding: utf-8 # # Making a choropleth # Choropleths are a way to represent some non-geographical data that varies by regions on your map. We'll be making choropleths with Folium and Geopandas. # # We're going to start with a dataset from the World Bank on Internet usage in 2016. # In[1]: import pandas import matplotlib.pyplot as plt # In[2]: internet = pandas.read_csv('data/world_internet_usage_2016.csv', skiprows=18, names=["name", "internet_use"]) internet.head() # In[3]: internet[internet.internet_use.isnull()] # In[4]: internet.dropna(inplace=True) internet.head() # ### Geopandas # In[5]: import geopandas world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) world.head() # In[6]: len(set(world.name) & set(internet.name)) # In[7]: len(set(world.name) - set(internet.name)) # In[8]: len(set(internet.name) - set(world.name)) # In[9]: world = world.merge(internet, how='left', on='name') world.head() # I'm going to copy over some Proj4 strings, that we can use to tell the underlying projection libraries, PyProj and Proj.4, how to project our map. # In[10]: mercator = '+proj=merc' robinson = '+proj=robin' wgs84 = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' # Next, we'll clean up the map a bit by removing Antarctica (makes projecting a bit more difficult, and is irrelevant to what we're making anyway) and any filling any missing data about Internet connectivity with a zero. # In[11]: world = world[(world.name!="Antarctica")].fillna(0) # We'll make a copy of the DataFrame when we do the projections, so we don't get any weird geometric artifacts. # In[12]: # mercator projection worldMercator = world.to_crs(mercator) worldMercator.plot(figsize=(20,20), column='internet_use', cmap="OrRd", scheme="QUANTILES", k=5, legend=True) plt.axis('off') plt.title("Internet usage by country") plt.savefig('data/internet_choropleth_geopandas.png') plt.show() # ### Data munging # # ... # ### PySAL # # ... # ### Folium # # ... # ### References # # Folium choropleth: http://python-visualization.github.io/folium/quickstart.html#Choropleth-maps # # World bank data: https://data.worldbank.org/data-catalog/country-profiles