The world’s leading publication for data science, AI, and ML professionals.

Visualization in Python -Visualizing Geospatial Data

Learn how to use folium to easily display maps and markers

Photo by T.H. Chia on Unsplash
Photo by T.H. Chia on Unsplash

Visualizing geospatial data is one of the most interesting things you can do with your data, especially if your data already contains columns that can directly map to locations on the map. And for Python developers, there is no shortage of libraries that can do the job. In this article, I will show you a very simple way to quickly display your geospatial data on a map. Specifically, we will use the folium library.

What is folium?

folium is a Python wrapper for the leaflet.js library – a JavaScript library for plotting interactive maps. Using folium, you can now easily add geospatial visualization to your Python projects, directly in Jupyter Notebook.

To install folium, you can use the following command in Jupyter Notebook:

!pip install folium

Displaying a Map

The first thing you want to do with folium is to display a map. And so let’s use the following code snippet:

import folium
mymap = folium.Map(location = [1.366623, 103.821285], 
                   width = 950, 
                   height = 550,
                   zoom_start = 12, 
                   tiles = 'openstreetmap')
mymap

When you run the above code snippet, you will see the following interactive map:

As you can see from the above, the location is the latitude and longitude of Singapore (1.366623, 103.821285), and I also set the width and the height of the map. The zoom_start parameter sets the initial zoom level of the map – the higher the number, the more zoomed in the map is. The following figure shows the map at zoom level 15:

The following figure shows the map at zoom level 5:

Once the map is displayed, you can use the scroll wheel on your mouse to zoom in or out of the map. You can also use the + or – button on the map to do the same.

The tiles parameter specifies the tileset to use. The default tileset to use is openstreetmap. The next section will discuss tilesets in more details.

A tileset is a collection of raster or vector data broken up into a uniform grid of square tiles.

Switching between Tilesets

Different tilesets provide different ways to display the maps. You can use the following tilesets in folium:

  • Stamen Terrain
  • Stamen Toner
  • Stamen Water Color
  • cartodbpositron
  • cartodbdark_matter

Instead of fixing the map to use a particular tileset throughthe tiles parameter, you can add different tilesets to the map using the TileLayer class. The following statements in bold adds five tilesets to the current map:

import Folium
mymap = folium.Map(location = [1.366623, 103.821285], 
                   width = 950, 
                   height = 550,
                   zoom_start = 12, 
                   tiles = 'openstreetmap')
folium.TileLayer('Stamen Terrain').add_to(mymap)
folium.TileLayer('Stamen Toner').add_to(mymap)
folium.TileLayer('Stamen Water Color').add_to(mymap)
folium.TileLayer('cartodbpositron').add_to(mymap)
folium.TileLayer('cartodbdark_matter').add_to(mymap)
folium.LayerControl().add_to(mymap)
mymap

The LayerControl class displays the tiles icon on the map:

Image by author
Image by author

Clicking on the tiles icon shows the various tilesets that you can use for your map:

Image by author
Image by author

The following sections shows how each tileset looks like.

Stamen Terrain

The Stamen Terrain map shows the terrain, hill shadings and natural vegetarian colors.

Image by author
Image by author

Stamen Toner

The Stamen Toner map is useful for visualizing features like river meanders and coastal zones.

Image by author
Image by author

Stamen Water Color

The Stamen Water Color map, well, as its name implies, renders the map using water color effects.

Image by author
Image by author

If you are interested in how the Stamen Water Color tileset is created, head over to https://hi.stamen.com/watercolor-process-3dd5135861fe.

Stamen is a data visualization design studio based in San Francisco, California. Its clients include National Geographic, Facebook and The Dalai Lama. Source: https://en.wikipedia.org › wiki › Stamen_Design

cartodbpositron

The cartodbpositron map is the base map from CARTO (formerly known as CartoDB). CARTO is a Software as a Service cloud computing platform that provides GIS, web mapping, and spatial data science tools.

Image by author
Image by author

cartodbdark_matter

The cartodbdark_matter map is the equivalent of the cartodbpositron map in dark mode.

Image by author
Image by author

Annotating the Map

What makes Maps useful is their ability for us to add annotations to them. For example, I would want to display markers representing the locations of the various MRT stations in Singapore. And so in this section you will learn how to add markers to the folium map.

First, you need to get the locations of the various MRT stations in Singapore. For this, I will use the data from https://data.world/hxchua/train-stations-in-singapore.

The dataset is available to the public. However, you need to join data.world as a member in order to download this dataset.

The following statements in bold loads the CSV file as a Pandas dataframe:

import folium
mymap = folium.Map(location = [1.366623, 103.821285], 
                   width = 950, 
                   height = 550,
                   zoom_start = 12, 
                   tiles = 'openstreetmap')
folium.TileLayer('Stamen Terrain').add_to(mymap)
folium.TileLayer('Stamen Toner').add_to(mymap)
folium.TileLayer('Stamen Water Color').add_to(mymap)
folium.TileLayer('cartodbpositron').add_to(mymap)
folium.TileLayer('cartodbdark_matter').add_to(mymap)
folium.LayerControl().add_to(mymap)
import pandas as pd
df = pd.read_csv('mrtsg.csv')
display(df)
mymap

The dataframe looks like this:

We will be making use of three columns for this article:

  • STN_NAME (stattion name)
  • Latitude
  • Longitude

Displaying Markers

The first marker that we want to add to the map is a circle marker. This can be accomplished using the CircleMarker class. The following statements in bold basically combines the Latitude and Longitude columns using the zip() function, and then iterate through the collection of locations and add circle markers representing each MRT station:

import folium
mymap = folium.Map(location = [1.366623, 103.821285], 
                   width = 950, 
                   height = 550,
                   zoom_start = 12, 
                   tiles = 'openstreetmap')
folium.TileLayer('Stamen Terrain').add_to(mymap)
folium.TileLayer('Stamen Toner').add_to(mymap)
folium.TileLayer('Stamen Water Color').add_to(mymap)
folium.TileLayer('cartodbpositron').add_to(mymap)
folium.TileLayer('cartodbdark_matter').add_to(mymap)
folium.LayerControl().add_to(mymap)
import pandas as pd
df = pd.read_csv('mrtsg.csv')
display(df)
for lat, lng in zip(df['Latitude'], df['Longitude']):    
    station = folium.CircleMarker(
            location=[lat, lng],
            radius=8,
            color='red',
            fill=True,
            fill_color='yellow',
            fill_opacity=0.5)   
    # add the circle marker to the map
    station.add_to(mymap)
mymap

Here are all the markers on the map, each representing a MRT station:

You can zoom in to locate each station:

Displaying Markers with Popups

Sometimes it makes a lot more sense to display a marker that displays more information when the user clicks on it. In this case, you just need to add the popup attribute. Let me show you this using another marker type – Marker. The Marker class displays a simple stock Leaflet marker on the map.

The following statements in bold adds Marker objects to the map:

for lat, lng, name in 
    zip(df['Latitude'], df['Longitude'], df['STN_NAME']):
    # station = folium.CircleMarker(
    #         location=[lat, lng],
    #         radius=8,
    #         color='red',
    #         fill=True,
    #         fill_color='yellow',
    #         fill_opacity=0.5)   
    # station.add_to(mymap)

    station_name = folium.Marker(
            location=[lat, lng],
            popup = name,            
        )   
    station_name.add_to(mymap)
mymap

Note that the popup parameter also works with the CircleMarker class.

You can see the markers here as opposed to the circle markers we used earlier:

When you click on a maker, you will see a popup showing the name of the MRT station:

Summary

I hope this article provides fodder for you to explore the folium library in more details. I have barely scratched the surface of what folium can do. If you use folium in your real world projects, be sure to share it with our readers through the comments window. Have fun!

Join Medium with my referral link – Wei-Meng Lee


Related Articles