folium: create leaflet.js maps in Python

Emanuel Zgraggen - September 16th, 2022

Folium enables you to combine the Python ecosystem's data manipulation power with the leaflet.js library's strenghts in map visualization.

Folium makes it simple to view Python-manipulated data as an interactive leaflet map. Data can be linked to a map for choropleth visualizations, and sophisticated vector, raster, and HTML visualizations can be passed as markers on the map.

In the following example we load a geojson file containing the shapes of all zip codes in Massachusetts and join it with a dataframe that has population estimates per ZIP code.

import pandas as pd
import folium
from urllib.request import urlopen
import json

# load massachusetts zip geo json
with urlopen('https://raw.githubusercontent.com/OpenDataDE/State-zip-code-GeoJSON/master/ma_massachusetts_zip_codes_geo.min.json') as response:
    state_geo = json.load(response)

# load data with zip to population mapping
df = pd.read_csv('https://raw.githubusercontent.com/einblick-ai/data/main/mass-zip-population.csv?token=GHSAT0AAAAAABXSA5TXACHN7AD57IDWHVR2Y3D2QWQ')
df['zip'] = df['zip'].astype(str).str.pad(width=5, side='left', fillchar='0')

# setup map layer
m = folium.Map(location=[42.371824, -71.080926], zoom_start=8, tiles="cartodbpositron")
cp = folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=df,
    columns=["zip", "population"],
    key_on="properties.ZCTA5CE10",
    fill_color="YlGn",
    fill_opacity=0.5,
    line_opacity=0.2,
    legend_name="population",
).add_to(m)

# add 'population' to geodata by looking it up by zip code in the df
df_index = df.set_index('zip')
for s in cp.geojson.data['features']:
    if s['properties']['ZCTA5CE10'] in df_index.index:
        s['properties']['population'] = f"{float(df_index.loc[s['properties']['ZCTA5CE10'], 'population']):,}" 
  
# adding a tooltip to the map
folium.GeoJsonTooltip(['ZCTA5CE10', 'population']).add_to(cp.geojson)
folium.LayerControl().add_to(m)
m

Start using Einblick

Pull all your data sources together, and build actionable insights on a single unified platform.

  • All connectors
  • Unlimited teammates
  • All operators