Represent your Geospatial Data using Folium
By: Slavvy Coelho
Tags: Geospatial, Visualization, GIS, Maps, Data Science

Represent your Geospatial Data using Folium

Photo by Valentin Antonucci from Pexels

As a part of the Data Science community, Geospatial data is one of the most crucial kinds of data to work with. The applications are as simple as ‘Where’s my food delivery order right now?’ and as complex as ‘What is the most optimal path for the delivery guy?’

What brought me to Folium?

I was recently working on a data science problem involving a lot of gps coordinates. Obviously the very basic question — how do I represent these coordinates on a map in my jupyter notebook? And while we know that plotly, geopy and basemap get the job done, this is the first time I came across Folium and decided to give it a go!

This article is a step by step tutorial on representing your data using folium.

Introduction

Folium essentially is used for generating interactive maps for the browser (inside notebooks or on a website). It uses leaflet.js , a javascript library for interactive maps.

To put it in a one-liner: Manipulate your data in Python, then visualize it in on a Leaflet map via folium.

Step 1: Installing folium on the computer and importing the necessary packages.

!pip install folium import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

from sklearn import preprocessing

import scipy ## for geospatial

import folium

import geopy

We will work with the Fire from Space: Australia dataset.

Step 2: Loading and inspecting the dataset.

df = pd.read_csv("fire_archive_M6_96619.csv")

Step 3: Finding the coordinates to begin with.

We can either pick a set of coordinates from the dataset itself or we can use geopy for this purpose. Here, we are talking about Australian wildfires so I started with Melbourne for reference.

city = "Melbourne"

# get location

locator = geopy.geocoders.Nominatim(user_agent="My app")

city = locator.geocode(city)

location = [city.latitude, city.longitude]

print(city, "

[lat, long]:", location)

Step 4: Plotting on the map.

Plotting points on a map in Folium is like building a house. You lay the base (that’s your background map) and then you add points on top of it’s surface.

We shall first lay the base.

map_ = folium.Map(location=location, tiles="cartodbpositron",

zoom_start=8)

map_

You can also play around with the tileset and zoom by referring here.

Now we plot the points on the map. We shall color-code according to the attribute ‘type’ and size it as per the ‘brightness’ of the fire. So let’s get those attributes in order first.

# create color column to correspond to type

colors = ["red","yellow","orange", "green"]

indices = sorted(list(df["type"].unique()))

df["color"] = df["type"].apply(lambda x:

colors[indices.index(x)])

## scaling the size

scaler = preprocessing.MinMaxScaler(feature_range=(3,15))

df["size"] = scaler.fit_transform(

df['brightness'].values.reshape(-1,1)).reshape(-1)

We finally add points on top of the map using folium.

df.apply(lambda row: folium.CircleMarker(

location=[row['latitude'],row['longitude']],

popup=row['type'],

color=row["color"], fill=True,

radius=row["size"]).add_to(map_), axis=1)

Finally, we move to adding a legend to the map. I used this reference for adding a legend. There are a variety of other methods but this was what I found the easiest.

legend_html = """<div style="position:fixed;

top:10px; right:10px;

border:2px solid black; z-index:9999;

font-size:14px;"> <b>"""+color+""":</b><br>"""

for i in lst_elements:

legend_html = legend_html+""" <i class="fa fa-circle

fa-1x" style="color:"""+lst_colors[lst_elements.index(i)]+"""">

</i> """+str(i)+"""<br>"""

legend_html = legend_html+"""</div>"""

map_.get_root().html.add_child(folium.Element(legend_html)) #plot

map_

Here’s the whole piece of code:

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

from sklearn import preprocessing

import scipy

## for geospatial

import folium

import geopy df = pd.read_csv("fire_archive_M6_96619.csv") city = "Melbourne"

# get location

locator = geopy.geocoders.Nominatim(user_agent="My app")

city = locator.geocode(city)

location = [city.latitude, city.longitude]

print(city, "

[lat, long]:", location) map_ = folium.Map(location=location, tiles="cartodbpositron",

zoom_start=8) # create color column to correspond to type

colors = ["red","yellow","orange", "green"]

indices = sorted(list(df["type"].unique()))

df["color"] = df["type"].apply(lambda x:

colors[indices.index(x)])

## scaling the size

scaler = preprocessing.MinMaxScaler(feature_range=(3,15))

df["size"] = scaler.fit_transform(

df['brightness'].values.reshape(-1,1)).reshape(-1) df.apply(lambda row: folium.CircleMarker(

location=[row['latitude'],row['longitude']],

popup=row['type'],

color=row["color"], fill=True,

radius=row["size"]).add_to(map_), axis=1) legend_html = """<div style="position:fixed;

top:10px; right:10px;

border:2px solid black; z-index:9999;

font-size:14px;"> <b>"""+color+""":</b> <br>"""

for i in lst_elements:

legend_html = legend_html+""" <i class="fa fa-circle

fa-1x" style="color:"""+lst_colors[lst_elements.index(i)]+"""">

</i> """+str(i)+"""<br>"""

legend_html = legend_html+"""</div>"""

map_.get_root().html.add_child(folium.Element(legend_html))

#plot

map_

You can also find it on my Github. Hope this article helped.