# Geospatial Data Visualization in Python with Folium

- Canonical: https://33rdsquare.com/geospatial-visualization-via-folium-library/
- Published: 2024-09-03
- Author: Jordan Brown
- Categories: [Artificial Intelligence & Machine Learning & ChatGPT](https://33rdsquare.com/category/tech/ai/)

---

## Introduction to Geospatial Visualization

Geospatial data is any data related to locations on the Earth‘s surface. This could be anything from the elevation of a mountain to the population density of a city to the flight path of an airplane. Geospatial data is often visualized on maps to make it easier to understand and gain insights from.

Geospatial visualization is the process of representing geospatial data on maps or other visual formats. With the rise of big data, geospatial visualization has become an increasingly important tool for making sense of large and complex location-based datasets.

Python has emerged as a popular language for geospatial data science and visualization, thanks to powerful libraries like Folium. In this guide, we‘ll take a deep dive into geospatial visualization with Folium and learn how to create interactive maps to explore and communicate insights from location data.

## What is Folium?

[Folium](https://python-visualization.github.io/folium/) is a Python library that makes it easy to create interactive maps with location data. It‘s built on top of the popular Leaflet.js mapping library, but allows you to manipulate your maps using Python instead of JavaScript.

With Folium, you can create maps with multiple layers, custom markers and pop-ups, choropleth map visualizations, and more. Folium supports several map tile providers, including OpenStreetMap, Mapbox, and Stamen, allowing you to choose the base map style that works best for your visualization.

Some key features of Folium include:

- Interactive panning and zooming
- Marker and popup support
- GeoJSON and TopoJSON overlays
- Chloropleth maps
- Heatmaps
- Vincent/Vega visualizations
- Fullscreen mode
- And more

Best of all, Folium is free, open source, and easy to learn even if you‘re new to mapping and geospatial data science. So let‘s get started!

## Installing Folium

Before we dive in, you‘ll need to install Folium. If you‘re using Anaconda or Miniconda, you can install Folium from the conda-forge channel with:

```
conda install -c conda-forge folium
```

Alternatively, you can install Folium using pip:

```
pip install folium
```

Once Folium is installed, we can import it along with other libraries we‘ll need in this guide:

```
import numpy as np
import pandas as pd
import folium
```

## Your First Folium Map

Now that we have Folium installed and imported, let‘s create our first map. We‘ll start by creating a simple map showing the center of the United States.

```
# Create a map centered on the US
us_map = folium.Map(location=[39.8283, -98.5795], zoom_start=4)

# Display the map
us_map
```

Here we created a `folium.Map` object centered on latitude 39.8283 and longitude -98.5795 (the geographic center of the contiguous US) with an initial zoom level of 4. Calling the map object displays it inline in a Jupyter notebook.

That‘s all there is to it! You‘ve created your first interactive map with Folium. You can click and drag to pan around, use the +/- buttons or your scroll wheel to zoom in and out, and click markers to display pop-ups (though we haven‘t added any yet).

## Customizing Your Map

Folium provides several options for customizing the appearance and behavior of your maps. For example, you can change the base map tiles to give your map a unique style.

Folium supports several built-in tile sets, including:

- OpenStreetMap
- Stamen Terrain
- Stamen Toner
- Mapbox Bright
- And more

To change the tile set, simply pass the name of the desired tileset to the `tiles` parameter when creating your map:

```
stamen_map = folium.Map(location=[39.8283, -98.5795], zoom_start=4, tiles=‘Stamen Toner‘)
stamen_map
```

This creates a map with the black and white Stamen Toner tileset, giving it a unique minimalist style. Experiment with different tilesets to find one that matches your visualization style.

You can also change the center location and zoom level of your map by passing different values to the `location` and `zoom_start` parameters:

```
eu_map = folium.Map(location=[50.8503, 4.3517], zoom_start=4)
eu_map
```

This map is centered on Brussels, Belgium with a zoom level of 4, showing most of Europe.

## Adding Markers and Pop-Ups

Markers allow you to highlight specific locations on your map, while pop-ups let you display additional information about those locations. Folium makes it easy to add markers and pop-ups to your maps.

To add a marker, use the `folium.Marker` class:

```
# Create a map
m = folium.Map(location=[45.5236, -122.6750], tiles=‘Stamen Terrain‘)

# Add a marker for Mount St. Helens
folium.Marker([46.1912, -122.1944], popup=‘Mt. St. Helens‘).add_to(m)

# Display the map
m
```

Here we created a map centered on Portland, Oregon using the Stamen Terrain tiles, then added a marker for nearby Mount St. Helens. Clicking the marker will display a pop-up with the text "Mt. St. Helens".

You can customize your markers by passing additional arguments to `folium.Marker`:

```
folium.Marker(
    [46.1912, -122.1944],
    popup=‘Mt. St. Helens‘,
    icon=folium.Icon(color=‘red‘, icon=‘info-sign‘)
).add_to(m)
```

This changes the marker icon to a red info sign. Folium supports many other marker styles as well.

You can also add pop-ups to the map itself, without an associated marker:

```
folium.Popup(‘Welcome to Portland!‘).add_to(m)
```

## Visualizing Geospatial Data

Now that you know the basics of creating and customizing maps with Folium, let‘s look at how to visualize real-world geospatial datasets.

For this example, we‘ll use a dataset of public on-street EV charging stations in Seattle. Let‘s start by loading the data into a Pandas DataFrame:

```
stations_df = pd.read_csv(‘https://raw.githubusercontent.com/avishek4redacled/blogathon/main/Seattle_Charging_Stations.csv‘)
stations_df.head()
```

The dataset contains columns for the station name, operator, number of charging ports, location, and more.

To plot the stations on a map, we‘ll create a Folium map centered on Seattle, then add a marker for each charging station:

```
# Create a map centered on Seattle
seattle_map = folium.Map(location=[47.6062, -122.3321], zoom_start=12)

# Add a marker for each station
for idx, row in stations_df.iterrows():
    folium.Marker([row[‘Latitude‘], row[‘Longitude‘]],
                  popup=row[‘Station Name‘]).add_to(seattle_map)

# Display the map
seattle_map
```

Now we have an interactive map of Seattle showing the locations of all on-street public charging stations! You can click on any marker to see the name of that particular charging station.

We can make our map even more informative by styling the markers according to the charging station operator. Let‘s create a dictionary mapping operators to marker colors:

```
operator_colors = {
    ‘City of Bellevue‘: ‘blue‘,
    ‘Seattle City Light‘: ‘green‘,
    ‘Puget Sound Energy‘: ‘purple‘
}
```

Then we can pass the appropriate color when creating each marker:

```
for idx, row in stations_df.iterrows():
    folium.Marker([row[‘Latitude‘], row[‘Longitude‘]],
                  popup=row[‘Station Name‘],
                  icon=folium.Icon(color=operator_colors[row[‘Operator‘]])).add_to(seattle_map)
```

Now the map shows charging stations operated by the City of Bellevue in blue, Seattle City Light in green, and Puget Sound Energy in purple. This makes it easy to see at a glance who operates each station.

There are many other possibilities for visualizing and styling geospatial data with Folium – this is just scratching the surface! With a bit of creativity, you can create powerful interactive visualizations that bring your spatial data to life.

## Real-World Applications

Geospatial data visualization has countless real-world applications across many industries, from urban planning and logistics to public health and environmental conservation. Some examples include:

- Visualizing urban growth and development patterns over time
- Mapping disease outbreaks and modeling their spread
- Planning optimal delivery routes and optimizing supply chain logistics
- Assessing vulnerability to natural hazards like floods, hurricanes, and wildfires
- Identifying promising locations for solar or wind energy installations
- Monitoring deforestation and habitat loss
- Mapping election results and voter turnout
- And many more

As geospatial data becomes increasingly ubiquitous, being able to create compelling interactive visualizations is becoming an essential skill for data scientists, analysts, and researchers.

## Learn More

To learn more about geospatial visualization with Python and Folium, check out these resources:

- [The official Folium documentation](https://python-visualization.github.io/folium/)
- [Web Mapping with Folium](https://geobgu.xyz/web-mapping/index.html) from the Ben-Gurion University of the Negev
- [Folium Plugin & Heatmap Examples](https://github.com/jdamiani27/Data-Visualization-and-D3/blob/master/Lessons/03-Geographic-Mapping-Python/Notebooks/06-Folium-Plugin-Heatmap-Examples.ipynb) from the GitHub repo of Johnny Damiani
- [Mapping with Python](https://www.youtube.com/watch?v=Vm5pcPz1S5k) and [Interactive Mapping with Python and Folium](https://www.youtube.com/watch?v=L6lKJ5_Vvso) from the Earth Lab Analytics Hub

I hope this guide has helped you get started with geospatial visualization using Python and Folium. With these tools at your disposal, you‘re well equipped to explore the exciting world of geospatial data science. Happy mapping!

---

Source: [Geospatial Data Visualization in Python with Folium](https://33rdsquare.com/geospatial-visualization-via-folium-library/)
