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 apop-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) map_osm
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) arrest_table.dropna(subset=['Race'],inplace=True) def race_col(x): if x=='B': return 'black' if x=='W': return 'blue' if x=='A': return 'yellow' if x=='H': return 'red' else: 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)