

Interactive Geographical Maps with GeoPandas
Data VisualizationModelingGeoPandasposted by Parul Pandey December 23, 2021 Parul Pandey

The word geospatial is composed of two distinct terms. Geo means Earth, and Spatial means relating to or occupying space. Together it refers to the time-based data pertaining to a specific location on the Earth’s surface. GeoPandas is a popular library used to analyze and work with geospatial data in Python. In one of its recent updates, the library has added methods and utilities to support interactive visualizations. This is a great addon to an already helpful library.

Highlights of the latest release in GeoPandas library: Source: https://geopandas.readthedocs.io/en/latest/docs/changelog.html#version-0-10-0-october-3-2021
In this article, we’ll explore the interactivity of GeoPandas in detail. We’ll begin by introducing GeoPandas briefly and then move on to some of its visualizations capabilities.
Geopandas
GeoPandas is a widely used open-source library for working and manipulating geospatial data in Python. It extends the functionalities of a pandas’ DataFrame, thereby making it possible to handle spatial data within pandas →hence the name. In a way, GeoPandas combines the power of pandas with Shapley. Shapley is a Python package for manipulation and analyzing geometric objects in the Cartesian plane.
Installation
Geopandas can be installed with conda
, pip
Or directly from the source
. However, the preferred way is to use conda since it provides pre-built binaries for all platforms (Windows, Mac, Linux).
conda install -c conda-forge geopandas
Additionally, folium, matplotlib, and mapclassify packages are also required for interactivity to work. You can install them using:
conda install -c conda-forge folium matplotlib mapclassifyorpip install folium matplotlib mapclassify
Refer to the installation guide for detailed instructions and gotchas.
First steps with GeoPandas
If this is your first time hearing about GeoPandas, I recommend going through this short tutorial. This tutorial will help you get acquainted with the library quickly. In a nutshell, GeoPandas builds up on Pandas library, making it compatible with geospatial data.

GeoPandas builds up on Pandas library | Image by Author
GeoPandas uses the GeoSeries
and GeoDataFrame
types which are in turn subclasses of pandas.Series
and pandas.DataFrame
respectively. The figure above visualizes the relationship between the two.
In this section, we’ll look at the basic functionalities of GeoPandas, i.e., plotting static maps. This section builds up the necessary base required for the next section, which involves creating interactive visualizations.
🔗 You can access the code notebook from 👇
Importing the libraries
After GeoPandas has been successfully installed, we can import it and verify whether the latest version has been installed on our system.
import geopandas
import matplotlib.pyplot as plt
print(geopandas.__version__)
------------------------------------------
0.10.2
Reading in the data
Let’s use the inbuilt GeoPandas datasets for the demo. Later in this article, we’ll also learn how to work with our own data. GeoPandas comes with three pre-made maps which can be easily accessed as follows:
geopandas.datasets.available
----------------------------------------
['naturalearth_cities', 'naturalearth_lowres', 'nybb']
Where
- naturalearth_lowres → contours of countries
- naturalearth_cities → positions of cities
- nybb → New York boroughs
Let’s use the naturalearth_lowres
option and display the dataset.
world_filepath = geopandas.datasets.get_path('naturalearth_lowres')
world = geopandas.read_file(world_filepath)
world.head()

A GeoPandas dataframe | Image by Author
As mentioned above, we get a GeoPandas dataframe with a distinct geometry column. Along with that, information like GDP and population of the various countries is also obtained.
Visualizing the data
To plot the active geometry, we’ll call theGeoDataFrame.plot().
This method generates a plot of the geometry column using matplotlib under the hood.
world.plot()

Image by Author
The output is a world map created using a single line of code. We can also play with the available parameters to create multiple variations in the plot obtained.
- Color coding by a specific column
Let’s say we want to visualize the world population country-wise. To do that, we’ll pass the column pop_est
I.e., the column in the dataframe specifying the population as the first argument. Technically, the geometry column is still plotted, but the plot is color-coded by the pop_est
column.
world.plot('pop_est', legend=True,figsize=(12,8))
plt.title('World Population')

Image by Author
The most populated countries are depicted in shades of yellow and light green, while those with the least population are shown in purple.
- Colormaps
If you do not like the default map color, you can easily modify it using the cmap
attribute. For a list of compatible options, visit the official matplotlib site. The default colormap is viridis
. Let’s look at a couple of more colormaps and how they render the map:
🎨 Set2
cmap='Set2'
world.plot('pop_est', cmap=cmap, legend=True,figsize=(12,8))
plt.title(f'World Population with colormap: {cmap}')

Image by Author
🎨 magma
cmap='magma'
world.plot('pop_est', cmap=cmap, legend=True,figsize=(12,8))
plt.title(f'World Population with colormap: {cmap}')

Image by Author
- Boundaries
It is also possible to display just the map boundary.
world.boundary.plot(figsize=(12,8))

Image by Author
Plotting Interactive Maps
All the plots in the previous section are static in nature. This means we cannot interact with them with functionalities like zoom, pan, hover, or popups. However, the explore
method gives the ability to convert the static maps into their interactive counterparts.
Syntax
GeoDataFrame.explore()
There isn’t much difference in usage. The explore()
method returns a folium.Map
object that renders an interactive map. Let’s transform the static population world map created above into an interactive one.
world.explore(column='pop_est',cmap='Set2')

Image by Author
With a slight modification, we have a fully interactive chart. Let’s create a new chart displaying only the GDP for the Asia region. Since GeoPandas is an extension of pandas, we can easily filter columns based on a condition.
Calculating GDP for Asia
asia = world[world['continent'] =='Asia']
asia.explore(column='gdp_md_est',cmap='Set2')

Image by Author
Parameters
In the above example. we have only used two parameters i.e. column
and cmap
. However, the explore()
method comes with a lot of useful parameters. Some of the interesting ones are as follows:
- tooltip
The tooltip
parameter, which defaults to True
displays the GeoDataFarme attributes when hovering over the object. It can be deactivated by setting it to False.
asia = world[world['continent'] =='Asia']
asia.explore(column='gdp_md_est',cmap='Set2',tooltip=False)
We can also pass the string or a list of strings to specify only those columns that need to be included. In the map below, we only want the name of the country and its corresponding GDP value. Hence, we’ll specify the same in the tooltip parameter.
asia = world[world['continent'] =='Asia']
asia.explore(column='gdp_md_est',
cmap='Set2',
legend=False,
tooltip=['name','gdp_md_est'])

Image by Author
2. popup
If the tooltip parameter is enabled, the attributes become visible on a simple hover. Another option is to enable them selectively by using the popup option. The good thing about using a popup is that the attribute information is displayed only when clicked. Here also, we can pass the string or list of strings to specify the columns to be included.
asia = world[world['continent'] =='Asia']
asia.explore(column='gdp_md_est',
cmap='Set2',
legend=False,
tooltip=False
popup=['name','gdp_md_est'])

Image by Author
3. tiles
This parameter specifies the tile to be used. The built-in options include :
OpenStreetMap, Stamen Terrain, Stamen Toner, Stamen Watercolor, CartoDB positron, CartoDB dark_matter where OpenStreetMap is used by deafult.
asia = world[world['continent'] =='Asia']asia.explore(column='gdp_md_est', legend=False, tiles=<enter the name of the tile to be used>)

Image by Author
4. legend
This parameter decides whether to show the legend on the map or not.
5. style_kwds
If some additional style needs to be passed, the style_kwds
is the go-to parameter. For instance, whether to draw a boundary on a map, the color of the boundary, opacity, fill option can be controlled by this parameter. As an example, let’s say we want to display the Asia GDP map wherein the boundaries are colored red with a width = 0.2 and opacity level of 0.1.
asia = world[world['continent'] =='Asia']
asia.explore(column='gdp_md_est',
cmap='Set2',
legend=False,
style_kwds=dict(color="black",weight=3, opacity=0.4))

Image by Author
Using your own data
Till now, we have used the custom datasets that come preloaded with the library. In reality, we would like to work with our own datasets. A dataset containing a latitude
and a longitude
column can be easily converted into a GeoPandas dataframe. To demonstrate the technique, I’m borrowing the dataset from my article below:
Visualizing India’s Seismic activity
This dataset includes a record of the date, time, location, depth, magnitude, and source of every Indian earthquake since 2018. Let’s import the data and look at the various attributes.
df = pd.read_csv('Indian_earthquake_data.csv')
df.head(10)
Since the dataframe has a latitude and longitude column, it can be easily converted to a GeoPandas Dataframe.
from geopandas import GeoDataFrame from geopandas import points_from_xygeometry = points_from_xy(df['Latitude'],df['Longitude']) df2 = GeoDataFrame(df, geometry=geometry) df2.head()

Image by Author
Conclusion
This article looked at the versatile GeoPandas library and how it shines while working with geospatial data in Python. We first learnt about its basic usage and then moved on to a newer interactive functionality. I’m sure you’ll like to explore the library further and use it with your own datasets to perform analysis. Geospatial analytics is a fascinating field, and GeoPandas does the primary heavy lifting so that users can focus more on the problem at hand than the tools.
Article originally posted here. Reposted with permission.