Creating Contour Lines on Folium Map with Python

Contour lines to add an extra dimension to you visualisations and maps

Djuwita Carney
Analytics Vidhya
4 min readDec 5, 2019

--

Photo by Annie Spratt on Unsplash

Credits:

In many cases, we might encounter the need to put a third dimension such as elevation, rainfall rate, temperature, population and many others on the 2-D map. Creating contour lines is one way to do so. This article will guide you through step by step process in creating contour lines on Folium with Python.

Required libraries for this process are :

numpy, pandas, folium, branca, matplotlib.pyplot, scipy.interpolate, geojsoncontour, scipy, Raster2xyz, tiffile and rasterio. Some of them are those that commonly used, but the rest are special for mapping. Depending on what file format you have for your third dimension data, you might be able to skip some of the codes, or you might need to use different tools to read different file format. In this example, we will use a DEM (Digital Elevation Model) in TIFF format.

Reading DEM in TIFF and display it.

The above codes results in the following figure. If this is the only thing you need, then you are all set.

Key West, Florida Map Produced from Digital Elevation Model

The figure above shows the map in x,y coordinates, and mainly shows elevations lower than mean sea level of zero. We might want to have more information out of the DEM, such as ground surface elevation. We might need to create contour lines to show more informative map. Let’s create contour lines and display it on Folium.

Contour Lines Generation

First, we would like to save our image in csv format as follows:

In order to display our map on Folium, we need to transform our coordinates into longitude and latitude format. The loop below will do the job. However, keep in mind that depends on the file size, this process can be very time consuming. For a practice, use a small datasets to make sure that your codes work.

Now we are ready to create the contour elevation of Key West Map. To do this, we need to import some libraries.You might have to pre-install some of them if you have not done so.

The above code creates contour lines in MatPlotLib format. This is not compatible with Folium map. Therefore, we need to convert this contour into GeoJson format with the following code.

The following figure is our contour elevation map for Key West, Florida.

Contour Map of Key West, Florida

Enjoy creating maps, I hope I can share more mapping tricks with you.

Data resources: NOAA (National Oceanography and Atmospheric Agency)

--

--