Site icon Roel Peters

Plot a Choropleth Map with Folium and GeoPandas

In this blog post, we’ll use GeoPandas and Folium in Python to plot a choropleth map of New York’s unemployment rate per borough. Not because it’s extremely interesting, but because it took me a while to get all the elements in order, and I want to help you save some time.

import folium
import pandas as pd
import geopandas as gpd

path = gpd.datasets.get_path('nybb')
df = gpd.read_file(path)
df = df.to_crs(epsg = 4326)
df['unemployment'] = pd.Series([4.0, 4.6, 4.5, 4.2, 9.1])
df['BoroCode'] = df['BoroCode'].apply(lambda x: str(x))

This is the resulting table:

Next, we’ll turn our geometry column into a GeoJSON.

geo = gpd.GeoSeries(df.set_index('BoroCode')['geometry']).to_json()

Next, create the Choropleth.

m = folium.Map(location = [40.70, -73.94], zoom_start = 10)
folium.Choropleth(
    geo_data = geo,
    name = 'Choropleth',
    data = df,
    columns = ['BoroCode','unemployment'],
    key_on = 'feature.id',
    fill_color = 'YlGnBu',
    fill_opacity = 0.5,
    line_opacity = 1,
    legend_name = 'Unemployment (%)',
    smooth_factor=  0
).add_to(m)

Finally, render the map. Due to the complexity of the polygons, you might want to use the following method instead of simply printing the map if you’re using Jupyter.

def embed_map(m):
    from IPython.display import IFrame
    m.save('index.html')
    return IFrame('index.html', width='100%', height='750px')
embed_map(m)

And there we go:

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

Exit mobile version