avatarAmit Kulkarni

Summary

The provided content introduces the use of the Python library Folium for creating interactive geospatial maps, detailing various features such as adding markers, tile layers, and generating heatmaps and choropleths to visualize geospatial data effectively.

Abstract

The web content is a comprehensive guide to geospatial data visualization using the Folium library in Python. It begins by explaining the significance of geospatial visualization and how Folium simplifies the process of creating interactive maps. The article then guides the reader through setting up a development environment, the basics of using Folium, and demonstrates various mapping techniques, including the addition of markers, highlighting specific areas, and incorporating different tile layers for map customization. It also illustrates the creation of choropleth and heatmaps using real-world tornado data to depict patterns and trends. The author emphasizes the user-friendliness of Folium and its utility for both beginners and professionals in fields requiring geospatial analysis. The article concludes with a reflection on the power of Folium for data visualization and decision-making, inviting readers to explore further and connect with the author on LinkedIn and GitHub.

Opinions

  • The author believes that geospatial data visualization is a powerful method for making sense of location-based information, suggesting that it can present complex data in an accessible visual format.
  • Folium is presented as a robust and user-friendly Python library that is particularly suitable for those new to programming, indicating its ease of use and minimal coding requirements.
  • The article suggests that interactive and dynamic geospatial visualizations can greatly enhance decision-making across various fields, implying their importance in data analysis.
  • By showcasing different types of maps and visualizations, the author conveys the versatility and adaptability of Folium to meet various data visualization needs.
  • The inclusion of real-world examples, such as tornado data analysis, underscores the practical applicability of Folium in real-world scenarios and research.
  • The comparison of Folium visualizations with those from Matplotlib demonstrates the author's view that Folium can produce results on par with or superior to other established visualization tools.
  • The provision of additional resources and FAQs reflects the author's commitment to providing comprehensive support and encouraging reader engagement with geospatial analysis.
  • The conclusion expresses the author's enthusiasm for Folium and the potential it holds for users interested in geospatial data visualization.

Interactive Geospatial Maps Using Folium in Python

Learn how to leverage the Folium and GeoPandas libraries to create interactive and dynamic geospatial visualizations in your Python projects

Source: Author

In this blog, we will cover the below topics

  • What is Folium?
  • Getting started with Folium
  • Creating our first map
  • Adding markers to map
  • Highlighting specific area
  • Adding Tile Layer to map
  • Creating heatmaps with Folium
  • Creating Choropleth map
  • Adding MiniMap
  • Conclusion
  • FAQ’s

What is Folium?

Geospatial data visualization is a powerful way to make sense of location-based information using maps and graphics. It helps people understand complex data by presenting it visually, making it accessible to a wide audience. With the help of Python libraries like Folium, you can easily create interactive and informative maps.

Folium, a robust Python library, simplifies the creation of various Leaflet maps. It has a user-friendly interface that simplifies the process of adding markers, highlighting areas, and creating heat maps. It requires a basic understanding of data wrangling using Python to generate informative and visually appealing maps.

Feel free to check the blog Introduction To Geospatial Analysis With Python and Visualizing Geospatial Information using GeoPandas in Python. It covers the basics of geospatial analysis using GeoPandas and Matplotlib for visualizing geospatial data.

Getting Started with Folium

Set up your development environment

Let us create a virtual environment, we will use the same environment for all the use cases that follow in the subsequent sections. Here are the steps to create a virtual development environment.

# STEP 1: Open the terminal and install the library virtualenv
pip install virtualenv

# STEP 2: Create a new virtual environment
virtualenv geospatial

# STEP 3: Activate the new virtual environment
geospatial\scripts\activate

Installation and setup of Folium in Python

We will need the below Python libraries namely GeoPandas for spatial analysis, Matplotlib for visualization, and Folium for maps.

# pip install geopandas
import geopandas as gpd
 
# pip install matplotlib
import matplotlib.pyplot as plt

# pip install folium
import folium

Let’s create our first map using Folium

We will set a location such that we see the map of the USA and set the zoom level to 4, the higher the zoom level granular the view.

from branca.element import Figure

map_initial = folium.Map(location = [40, -95], zoom_start = 4)
map_initial
Source: Author | World map sliced for North and South America

What if we need to focus on a specific location let’s say Disney Land? well, all we need to know is the latitude and the longitude. This data can be fetched from this site. We need to mention the place name to get the latitude and longitude of the selected place. Also, not that the map is based on the OpenStreetMap theme which is the default view.

map1 = folium.Map(location=[33.812092, -117.918976],zoom_start=14)
Source: Author | OpenStreetMap focussing on a specific location

Adding Markers to Maps

The above map has a lot of details in lane name and parking space etc. but it would be good to have a marker that points us to the place we are searching for and gets us additional information. Let’s use the marker feature to highlight the Disney land location and show its address as well.

# Adding markers to the map
marker_popup = folium.Marker(
    location=[33.812092, -117.918976],
    popup="<stong>Address: Disney Land, Anaheim, CA 92802, USA</stong>",
    tooltip= "Click here for more info")
marker_popup.add_to(map1)
map1
Source: Author | Using markers to highlight the location

Please note that we have hard-coded the address in the above code chunk but depending on the use case, this can be made dynamic. Also, there are various types of markers that can be showcased on the map.

Highlighting specific area

There may be cases where we need to highlight a certain location let’s say circle the Disney land location in blue color to make it prominent and easy to find.

# Adding circle markers to the map
marker_circle = folium.CircleMarker(
    location=[33.812092, -117.918976],
    popup="<stong>Address: Disney Land, Anaheim, CA 92802, USA</stong>",
    tooltip= "Click here for more info",
    color='blue',
    fill=True,    
    radius = 50)
marker_circle.add_to(map1)
map1
Source: Author | Using markers to circle the area

Adding Tile Layer to map

So far, we have seen the OpenStreetMap which is the default setup. But there are other themes to viewing the same map and moreover, it can be made interactive where the user can choose the theme. Let's explore this feature in this section. We will add 6 different layers to choose from and note the radio buttons at the right top corner.

folium.TileLayer('openstreetmap').add_to(map1)
folium.TileLayer('Stamen Terrain').add_to(map1)
folium.TileLayer('Stamen Toner').add_to(map1)
folium.TileLayer('Stamen Water Color').add_to(map1)
folium.TileLayer('cartodbpositron').add_to(map1)
folium.TileLayer('cartodbdark_matter').add_to(map1)
folium.LayerControl().add_to(map1)
map1
Source: Author | Various Tile Layers

So far, we have used hard-coded latitudes and longitude values to visualize the locations on the map. As we move to the next section, let’s use some real-world data to visualize the patterns with the Choropleth map and heatmaps of course with Folium as the base.

Dataset for analysis and visualization

We will use the tornado data from the US, this is the same data that we had used in the previous blog. Let’s load the state (base map) and tornado data and explore it. There are 63K rows and 23 columns.

states = geopandas.read_file("usa-states-census-2014.shp")
print(states.columns)
OUTPUT:
(58, 11)
Index(['STATEFP', 'STATENS', 'AFFGEOID', 'GEOID', 'STUSPS', 'NAME', 'LSAD',
       'ALAND', 'AWATER', 'region', 'geometry'],
      dtype='object')
tornado = geopandas.read_file("1950-2018-torn-initpoint.shp")
print(tornado.columns)
OUTPUT:
Index(['om', 'yr', 'mo', 'dy', 'date', 'time', 'tz', 'st', 'stf', 
        'stn', 'mag','inj', 'fat', 'loss', 'closs', 'slat', 'slon', 
        'elat', 'elon', 'len','wid', 'fc', 'geometry'],
      dtype='object')

We also observed in the previous blog that there are 3 more additional states in tornado data that are missing in the base map. For the sake of simplicity, let’s remove these regions from the analysis.

tornado_states_filtered = 
        tornado[tornado['st'].isin(list(states.STUSPS.unique()))]

Creating Choropleth map

Choropleth maps are a type of thematic map used to visualize and represent data across geographic areas. These maps use color or shading to convey information about a specific variable or attribute for different regions, such as countries, states, counties, or other administrative or geographic divisions. They provide a visual way to communicate complex information and can help identify disparities and trends that may not be apparent in raw data tables or charts.

Let’s plot the tornado data using the Choropleth map and to achieve this, we need information on the state and number of tornadoes in each state. We can easily get this information by using group by function.

state_level_tornadoes = 
    tornado_states_filtered[['st','cnt']].groupby('st').count().reset_index()

OUTPUT:
 st cnt
0 AL 2143
1 AR 1809
2 AZ 250
3 CA 436
4 CO 2174
....
43 VA 738
44 VT 44
45 WA 119
46 WI 1380
47 WV 139
48 WY 686
map4 = folium.Map(location=[48, -102], zoom_start=3)

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/main/examples/data"
)
state_geo = f"{url}/us-states.json"

folium.Choropleth(
    geo_data=state_geo,
    name='choropleth',
    data=state_level_tornadoes,
    columns=['st', 'cnt'],
    key_on='feature.id',
    fill_color='Paired',
    fill_opacity=0.75,
    line_opacity=0.3,
    legend_name='Impact of Tornadoes'
).add_to(map4)

map4
Source: Author | Choropleth map representing the Tornado trend

In the previous blog, we had done the same analysis but used Matplotlib to plot the tornado trends and in this blog, we have done the same using Folium. Here is the comparison. The trend seems to hold up nicely, the central part has high tornado activity and the Red region in the Choropleth map is the state of Texas with the highest number of tornadoes.

Source: Author | Comparing Chroropleth Vs Matplotlib - representing the same pattern

Adding MiniMap

A MiniMap is a small zoomed-out inset map. It is useful to get a bird's view of where the current map is on the world map. It is a small orange box at the right bottom corner of the map.

Source: Author | Use of MiniMap in visualization

Creating Heatmaps with Folium

Heatmaps are a type of data visualization that uses color intensity to represent the magnitude of a value. They are particularly useful for displaying complex data patterns and trends, especially when dealing with large datasets or when you want to highlight relationships and variations.

import folium.plugins as plugins
from folium.plugins import HeatMap

tornado_states_filtered['cnt'] = 1
tornado_states_filtered.columns
tornado_states_filtered['lon'] = tornado_states_filtered['geometry'].x
tornado_states_filtered['lat'] = tornado_states_filtered['geometry'].y
tornado_states_filtered['LatLong'] = list(zip(tornado_states_filtered.lat, tornado_states_filtered.lon))
tornado_states_filtered['LatLong'] = [list(tp) for tp in tornado_states_filtered['LatLong']]
tornado_states_filtered['LatLong_cnt'] = list(zip(tornado_states_filtered.lat, tornado_states_filtered.lon, tornado_states_filtered.cnt))

folium_heatmap = folium.Map(location=[33.812092, -117.918976],zoom_start=5)
folium_heatmap.add_child(plugins.HeatMap(tornado_states_filtered['LatLong_cnt'], radius=15))

folium_heatmap
Source: Author | Heatmap using Folium representing the Tornado trend

This also has similar patterns that we saw with Matplotlib and Choropleth maps.

Conclusion

Folium is a powerful Python library for geospatial data visualization. It’s a user-friendly tool that empowers anyone, from data analysts to business professionals, to create compelling maps and graphics. By transforming complex data into clear visuals, you can enhance decision-making and communication in various fields. Explore the world of geospatial data visualization and discover new perspectives on your data.

I hope you liked the article and found it helpful.

You can connect with me — on Linkedin and Github

My other Geospatial Analysis blogs

Introduction To Geospatial Analysis With Python Visualizing Geospatial Information using GeoPandas in Python

FAQs

Q1: Is Folium suitable for beginners who have little to no programming experience? A1: Yes, Folium is beginner-friendly. Its Python interface is relatively straightforward, and you can create basic maps and visualizations with minimal coding knowledge.

Q2: What are the other tools and software for Geospatial analysis? A2: Programming language like R is popular and is similar to Python. Also, tools like ArGis, QGis, and MATLAB are other options to consider

Q3: What are the real-world applications of geospatial visualization and folium? A3: Some of the common applications include displaying store locations, optimizing delivery routes, tracking vehicles and traffic conditions, mapping disease outbreaks and hotspots, urban development planning, and mapping crop yield and soil quality

Q4: Can I use my own geospatial data with Folium, or do I have to rely on built-in datasets? A4: You can import and visualize your custom data on Folium maps, allowing you to work with your specific datasets.

Q5: Are there any limitations to the types of visualizations I can create with Folium? A5: Folium offers a range of options like markers, pop-ups, etc. but you may need to combine Folium with other Python libraries like Matplotlib or Plotly. Folium is an excellent starting point, but depending on your needs, you can extend its capabilities as necessary.

References

GeoPandas

Matplotlib

In Plain English

Thank you for being a part of our community! Before you go:

Folium
Python
Visualization
Google Maps
Geopandas
Recommended from ReadMedium