How to make Interactive Maps with Folium

[This article was first published on Python – Predictive Hacks, and kindly contributed to python-bloggers]. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

Folium provides a python interface for leaflet.js. Leaflet.js is a Javascript library for interactive maps and can be useful to know on its own. The benefit of using this library via Folium is that Folium makes it very easy to use from within a Jupyter Notebook and to access your python data structures (e.g. Pandas DataFrames). The documentation for Folium can be found on its official website. For this tutorial we will work with the Baltimore Arrest Data

Interactive Map with Baltimore Arrest Data

The map will include the following dimensions:

  • Age: In the form of isAdult where will be a pop-up in every observation
  • Race: Will be a different color dot for each ethnicity race
  • The co-ordinates
  • The frequency of the incidents in a form of a heat-map.
import folium
from folium.plugins import HeatMap
import pandas as pd
import numpy as np

# load the data
arrest_table = pd.read_csv("Arrests.csv")

# create the isAdult variable
arrest_table['isAdult'] = np.where(arrest_table['Age']>=20,"Adult","Teenager")

# start the map of Baltimore
map_osm = folium.Map(location=[39.29, -76.61], zoom_start=11)
How to make Interactive Maps with Folium 1

Now, we will work with the Race and finally we will take a sample of 1K observations.

arrest_table = arrest_table.sample(n=1000, replace=False, random_state=1)


def race_col(x):
  if x=='B':
    return 'black'
  if x=='W':
    return 'blue'
  if x=='A':
    return 'yellow'
  if x=='H':
    return 'red'
    return 'green'

arrest_table['color_race'] = arrest_table['Race'].apply(lambda x:race_col(x) )

# Create the Heat Map
#Make the list of Lat an Long
lat = arrest_table.Latitude.tolist()
lng = arrest_table.Longitude.tolist()
HeatMap(list(zip(lat, lng))).add_to(map_osm)

# Add the Circles with the corresponding races based on the color
arrest_table.apply(lambda x:folium.Circle(location=[x['Latitude'], x['Longitude']], radius=50, fill=True, color=x['color_race'], popup=x['isAdult']).add_to(map_osm), axis=1)
How to make Interactive Maps with Folium 2
How to make Interactive Maps with Folium 3
To leave a comment for the author, please follow the link and comment on their blog: Python – Predictive Hacks.

Want to share your content on python-bloggers? click here.