When you’re working with geospatial knowledge in Python, then you definately would possibly wish to rapidly visualize that knowledge on a map. Python’s Folium library offers you entry to the mapping strengths of the Leaflet JavaScript library by way of a Python API. It lets you create interactive geographic visualizations which you could share as a website.
You’ll construct the online map proven beneath, which shows the ecological footprint per capita of many international locations and relies on a similar map on Wikipedia. Alongside the best way, you’ll be taught the fundamentals of utilizing Folium for knowledge visualization.
On this tutorial, you’ll:
- Create an interactive map utilizing Folium and reserve it as an HTML file
- Select from totally different internet map tiles
- Anchor your map to a particular geolocation
- Bind knowledge to a GeoJSON layer to create a choropleth map
- Fashion the choropleth map
When you work by way of the tutorial, then your interactive map will appear like this in the long run:
On this tutorial, you’ll create HTML recordsdata which you could serve on-line at a static webhosting service.
Another workflow is to make use of Folium within a Jupyter notebook. In that case, the Folium library will render your maps immediately within the Jupyter pocket book, which provides you alternative to visually discover a geographical dataset or embody a map in your knowledge science report.
When you click on beneath to obtain the related supplies to this tutorial, then you definately’ll additionally get a Jupyter pocket book arrange with the code of this tutorial. Run the pocket book to see how properly Folium and Jupyter can play collectively:
Take the Quiz: Take a look at your information with our interactive “Python Folium: Create Net Maps From Your Information” quiz. Upon completion you’ll obtain a rating so you possibly can observe your studying progress over time:
Set up Folium
To get began, create and activate a digital setting and set up folium
and pandas
. You should use the platform switcher beneath to see the related instructions on your working system:
You should use many options of Folium with out pandas. Nonetheless, on this tutorial you’ll finally create a choropleth map utilizing folium.Choropleth
, which takes a pandas DataFrame
or Sequence
object as considered one of its inputs.
Create and Fashion a Map
A helpful and beginner-friendly function of Folium is which you could create a map with solely three traces of code. The map appears to be like good by default as a result of the underlying Leaflet JavaScript library works properly with a variety of totally different tile suppliers, which give high-quality map backgrounds on your internet maps.
Be aware: A tile for an online map is a picture or vector knowledge file that represents a particular geographical space. Tiled web maps seamlessly be part of a number of tiles to current a geographical space that’s bigger than a single tile.
Moreover, the library boasts engaging default types for map options and provides you a lot choices to customise the map to suit your wants precisely.
Show Your Net Map Tiles—in Fashion!
You wish to present knowledge on a world map, so that you don’t even want to fret about offering any particular geolocation but. Open up a brand new Python file in your favourite textual content editor and create a tiled internet map with three traces of code:
import folium
m = folium.Map()
m.save("footprint.html")
Whenever you run your script, Python creates a brand new HTML file in your working listing that shows an empty world map with the default settings supplied by Folium. Open the file in your browser by double-clicking on it and have a look:

You now have an honest internet map that already contains interactive controls within the high left nook. You may zoom additional into the map and watch how the map particulars replace as new internet tiles load.
Be aware: You’re inspired to decide on a extra descriptive title for the Map
object. On this tutorial, you’ll keep on with m
to make it as simple as doable to proceed your studying within the quickstart section of Folium, which makes use of the identical variable title.
The default tiles that the library supplies come from OpenStreetMap. Nonetheless, you possibly can change the type of your map by specifying a unique string for the tiles
parameter, which masses the online tiles from a unique tile supplier:
import folium
m = folium.Map(tiles="cartodb positron")
m.save("footprint.html")
Run your up to date script and reload the web page in your browser. You’ll see that the type of the world map has modified. The Positron basemap by Carto and Stamen is designed to offer viewers geospatial context whereas maintaining the visible influence of the basemap minimal so that you could showcase your individual knowledge:

The Folium library additionally supplies different built-in map tiles which you could select from by altering the argument that you just cross to tiles
. You may even present a Leaflet-style URL to a customized tile set.
Add a Geolocation and Modify the Zoom Stage
Chances are you’ll not at all times have knowledge that issues the entire world. If you wish to show solely a particular space of the globe, then you possibly can add values to a different parameter when creating the Map
object:
import folium
m = folium.Map(location=(49.25, -123.12), tiles="cartodb positron")
m.save("footprint.html")
For instance, in the event you enter a tuple with the latitude and longitude proven within the code snippet above, then the ensuing map is targeted on Vancouver, Canada:

Nonetheless, on this tutorial, you wish to construct a political world map, so it ought to present a clear view of all continents. Earlier, you didn’t cross any geolocation, so the map zoomed out too far. As a result of in actuality there is no planet B, you may set the middle location of your map northeast of Null Island and alter the beginning zoom degree to get a map that matches your objective properly:
import folium
m = folium.Map(location=(30, 10), zoom_start=3, tiles="cartodb positron")
m.save("footprint.html")
On this code, you’ve modified the location
coordinates and handed 3
to zoom_start
. This transformation focuses the world map on a place that provides you view of the world’s political group into international locations:

Be aware that the precise zoom begin degree will rely in your display screen measurement, so be happy to experiment with a unique setting that matches you higher. Additionally needless to say there won’t be a zoom degree and place to show the world map completely utilizing the Mercator projection—though this setting does include New Zealand! Your customers may also zoom and transfer of their browsers as a result of the map is interactive.
Add a GeoJSON International locations Layer
At this level, you’ve got a handsome world map as a basemap, and you’ve got the means to type it. Finally, you wish to get to a degree the place you possibly can plot your country-specific knowledge on high of this map. For that, you want a layer which you could connect with your knowledge. The ecological footprint knowledge that you just’ll work with is linked to political international locations, so that you’ll want data that defines the boundaries of every nation individually.
Be aware: When you can see nation borders on the basemap, needless to say this can be a tiled internet map that consists of many particular person photographs stitched collectively. Which tiles you’re viewing additionally will depend on the zoom degree. Subsequently, you possibly can’t entry the outlines or the world of a rustic on the present tiled internet map layer.
A great method to create an extra layer that describes nation boundaries is by linking to a GeoJSON file. When you don’t have a becoming GeoJSON file useful, then you possibly can hyperlink on to a URL that gives such a file for you.
On this tutorial, you’ll use GeoJSON knowledge created by the Natural Earth undertaking and supplied by way of the geojson.xyz service.
Be aware: You’re not tied to utilizing these companies and might present a unique GeoJSON supply. For instance, you may construct your individual GeoJSON knowledge by utilizing the visible internet device at geojson.io.
You’ll use the info from the useful resource known as admin 0 international locations, as a result of it supplies comparatively high-quality knowledge on political borders of nations. Create this extra map layer by passing the direct knowledge URL to GeoJson
:
1import folium
2
3political_countries_url = (
4 "http://geojson.xyz/naturalearth-3.3.0/ne_50m_admin_0_countries.geojson"
5)
6
7m = folium.Map(location=(30, 10), zoom_start=3, tiles="cartodb positron")
8folium.GeoJson(political_countries_url).add_to(m)
9
10m.save("footprint.html")
In traces 3 to five, you added the direct knowledge URL as political_countries_url
to your script. In line 8, you handed the URL as an argument to folium.GeoJson
. In the identical line, you chained a name to .add_to()
on the finish of your code and handed your Map
object (m
) to the tactic.
With this code, you requested Folium to create a brand new vector layer on high of your world map utilizing the GeoJSON supplied on the given URL. Run your script once more to exchange the outdated HTML file, then refresh your browser to see the updates:

Your world map now has an extra layer that shows the GeoJSON options that characterize the political international locations of the world. Nice! Now it’s time to attach the person international locations together with your knowledge and create a choropleth map.
Create a Choropleth Map With Your Information
Now that you just’ve added a vector layer representing political international locations to your world map, you possibly can join that layer with country-specific knowledge. You may fill the GeoJSON options with totally different colours relying on their related knowledge values. Such a map is known as a choropleth map.
On this tutorial, you’ll create a map that’s primarily based on a map from Wikipedia that visually shows the ecological footprint per capita for a lot of international locations:

Your closing map gained’t look precisely the identical, but it surely’ll be fairly much like the Wikipedia map proven above. Since you’re constructing the map as an interactive internet map, viewers can even be capable of zoom and pan across the map to examine elements of it in additional element.
Add the Information to Your Map
A visually attention-grabbing approach of plotting country-specific knowledge on a map is a choropleth map, which implies that you shade geographical items primarily based on aggregated values. The Folium library supplies a Choropleth
class for making a choropleth map layer.
You may exchange the GeoJson
layer that you just created earlier with a Choropleth
layer that’ll take each the GeoJSON and the ecological footprint knowledge as enter:
1import folium
2import pandas as pd
3
4eco_footprints = pd.read_csv("footprint.csv")
5political_countries_url = (
6 "http://geojson.xyz/naturalearth-3.3.0/ne_50m_admin_0_countries.geojson"
7)
8
9m = folium.Map(location=(30, 10), zoom_start=3, tiles="cartodb positron")
10folium.Choropleth(
11 geo_data=political_countries_url,
12 knowledge=eco_footprints,
13 columns=["Country/region", "Ecological footprint"],
14 key_on="function.properties.title",
15).add_to(m)
16
17m.save("footprint.html")
To arrange a choropleth map with Folium, it’s essential to present two datasets:
geo_data
takes a path to the GeoJSON geometries. On this case, you’re passing a URL, however you may additionally use an area file path or present the info immediately.knowledge
takes the ecological footprint knowledge that you just’ve loaded right into a pandas DataFrame.
Lastly, you additionally have to specify methods to join these two datasets with one another:
-
columns
takes a tuple with the names of the 2 DataFrame columns that you just wish to use for the map. The primary merchandise ought to be the important thing that’ll join the ecological footprint knowledge with the GeoJSON knowledge. On this case, you select the"Nation/area"
column as that key. The second merchandise factors to the info that you just wish to bind to the GeoJSON geometries, and that’s the info within the column named"Ecological footprint"
. -
key_on
takes a string in dot notation that specifies the variable within the GeoJSON knowledge that represents the opposite a part of the info hyperlink. For this map undertaking, you select to hook up with the"title"
key of a rustic’s GeoJSON knowledge. You will discover this key beneathproperties.title
for every function.
Relying on what dataset you’re employed with, you could wish to select totally different keys each in your DataFrame and within the GeoJSON knowledge.
If you wish to learn to discover the precise key in a GeoJSON construction, then you possibly can broaden the collapsible part beneath:
You need to begin the key_on
parameter with "function"
after which observe it with a dot-notation path to the worth that you just wish to hyperlink. This won’t appear intuitive while you first take a look at the content material of a GeoJSON file:
"kind": "FeatureCollection",
"options": [
"type": "Feature",
"properties":
"scalerank": 1,
"labelrank": 3,
"sovereignt": "Afghanistan",
"sov_a3": "AFG",
"adm0_dif": 0,
"level": 2,
"type": "Sovereign country",
"admin": "Afghanistan",
"adm0_a3": "AFG",
"geou_dif": 0,
"geounit": "Afghanistan",
"gu_a3": "AFG",
"su_dif": 0,
"subunit": "Afghanistan",
"su_a3": "AFG",
"brk_diff": 0,
"name": "Afghanistan",
"name_long": "Afghanistan",
"brk_a3": "AFG",
// ...
,
"geometry":
"type": "Polygon",
"coordinates": [
[
[
61.210817091725744,
35.650072333309225
],
[
62.230651483005886,
35.270663967422294
],
// ...
]
]
,
// ...
]
The geographical options, every representing a rustic on this case, are collected in a JSON array that’s keyed on "options"
.
The library then iterates over this array and accesses every particular person function beneath the variable "function"
, which is why Folium can get to the highlighted factor of every function by way of the trail "function.properties.title"
.
Discovering the precise key in your GeoJSON knowledge and developing the string that factors to it may be difficult. However when you’ve efficiently linked the 2 datasets, you possibly can run the script one other time to see the ecological footprint knowledge displayed as a choropleth in your world map:

Nice, your knowledge is mapped onto the GeoJSON layer! The international locations are coloured in another way primarily based on the info values of their respective ecological footprints. And within the high proper of the web page, you actually have a legend.
However this map doesn’t look fairly as significant because the map that you just noticed on Wikipedia. The default blue shade scheme doesn’t appear to specific the urgency of the state of affairs properly, and the darkish grey areas that characterize lacking knowledge take up an excessive amount of of the viewers’ consideration. Thankfully, Choropleth
has extra parameters that you should use to customise your map layer.
Fashion Your Folium Map
To efficiently talk a message by way of data visualization, it’s essential to perceive your dataset and the story that you just wish to inform. Typically it may possibly assist to iterate over your draft as a way to discover the visualization that works finest. The Folium library lets you faucet into the facility of Leaflet to switch your maps with extra parameters.
Adapt the Colour Scheme and Opacity
Beforehand, you’ve recognized that the default blue shade scheme isn’t an incredible match for the map that you just wish to construct, so that you wish to swap it out for a unique shade scheme. You additionally observed that lacking knowledge stands out an excessive amount of, so that you’ll attempt to scale back the visible influence of lacking knowledge. Lastly, including a descriptive title on your legend will make the map much more user-friendly:
1import folium
2import pandas as pd
3
4eco_footprints = pd.read_csv("footprint.csv")
5political_countries_url = (
6 "http://geojson.xyz/naturalearth-3.3.0/ne_50m_admin_0_countries.geojson"
7)
8
9m = folium.Map(location=(30, 10), zoom_start=3, tiles="cartodb positron")
10folium.Choropleth(
11 geo_data=political_countries_url,
12 knowledge=eco_footprints,
13 columns=("Nation/area", "Ecological footprint"),
14 key_on="function.properties.title",
15 fill_color="RdYlGn_r",
16 fill_opacity=0.8,
17 line_opacity=0.3,
18 nan_fill_color="white",
19 legend_name="Ecological footprint per capita",
20).add_to(m)
21
22m.save("footprint.html")
On this code snippet, you up to date the parameters that you just use with Choropleth
as a way to enhance the visible show of your map layer:
-
Line 15 introduces
fill_color
, which you’ll be able to set to any Brewer color palette. You selected"RdYlGn_r"
, a divergent color scheme that goals to spotlight the intense values on each the excessive and the low ends. -
Line 16 provides
fill_opacity
with a price of0.8
. This setting adjustments the transparency of the fill shade in order that it turns into barely translucent. -
Line 17 units
line_opacity
to0.3
to de-emphasize each the border traces, which already present by way of the totally different fill colours for the international locations, and the underlying world map, which is seen as a result of adjusted translucency. -
Line 18 adjustments the default fill shade for lacking values from black to white by including the colour title as a string to
nan_fill_color
. -
Line 19 provides a title to the legend within the high proper of the map. This makes the map way more helpful, as a result of it permits your viewers to know what knowledge you’re displaying.
With these variations in place, your map appears to be like nearer to the map that you just’re modeling it on, and it’s extra user-friendly general:

The place are the international locations which have the best ecological footprint per capita? Can you discover the pink dots by zooming in on the map? These are a number of small international locations which have a really excessive ecological footprint per capita.
Be aware: The Brewer shade theme that you just used, "RdYlGn"
, exhibits low values as pink and excessive values as inexperienced by default. However that default shade scheme can be harder for viewers to parse as a result of pink and inexperienced have established meanings. Folks affiliate pink with doubtlessly harmful conditions and consider inexperienced as signifying that the whole lot is okay.
Subsequently, you wish to spotlight international locations the place individuals reside past the technique of our planet’s assets in pink colours and international locations that don’t in inexperienced. You may reverse the path of a Brewer shade scheme by including _r
on the finish of the colour palette’s title, which you’ve performed above.
Whereas the map appears to be like higher than earlier than, the present shade unfold doesn’t actually present which international locations have the best ecological influence general. You’ll enhance the visible story a bit extra by introducing customized binning subsequent.
Use Customized Information Binning
There are just a few international locations with a really massive ecological footprint worth per capita, and these international locations are fairly small. That is attention-grabbing to bear in mind, but it surely doesn’t work in favor of a world map view that goals to point out high-impact and low-impact international locations. Even when a small nation has a excessive ecological footprint per capita, a extra populous nation with a barely smaller ecological footprint per capita could have a better influence general.
The map on Wikipedia due to this fact introduces a customized data binning that, for instance, lumps all values greater than 8
into one bin. This method additionally highlights bigger international locations with a excessive ecological footprint per capita. You may observe go well with and use one other parameter of Choropleth
to outline a customized binning on your knowledge:
1import folium
2import pandas as pd
3
4eco_footprints = pd.read_csv("footprint.csv")
5max_eco_footprint = eco_footprints["Ecological footprint"].max()
6political_countries_url = (
7 "http://geojson.xyz/naturalearth-3.3.0/ne_50m_admin_0_countries.geojson"
8)
9
10m = folium.Map(location=(30, 10), zoom_start=3, tiles="cartodb positron")
11folium.Choropleth(
12 geo_data=political_countries_url,
13 knowledge=eco_footprints,
14 columns=("Nation/area", "Ecological footprint"),
15 key_on="function.properties.title",
16 bins=[0, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, max_eco_footprint],
17 fill_color="RdYlGn_r",
18 fill_opacity=0.8,
19 line_opacity=0.3,
20 nan_fill_color="white",
21 legend_name="Ecological footprint per capita",
22).add_to(m)
23
24m.save("footprint.html")
You fetch the utmost ecological footprint worth of all international locations in line 5 and reserve it to max_eco_footprint
. This worth is the higher certain on your customized binning. In line 16, you then use it along with the identical steps as within the Wikipedia map to outline customized bins on your dataset. Take one other take a look at your map:

After making use of the customized binning to your knowledge, the map higher represents the influence of all international locations with a comparatively excessive ecological footprint per capita. It does that by shifting the breakpoints for the colour palette so that each one international locations with a excessive ecological footprint present up in pink or variations of pink. This extra successfully raises consciousness of the potential hazard that may come from residing above the technique of our planet’s assets.
Add a Layer Management Ingredient
As a closing consumer expertise enchancment, you can even title your choropleth map layer and add a LayerControl
factor to the map in order that your viewers can toggle the choropleth layer:
import folium
import pandas as pd
eco_footprints = pd.read_csv("footprint.csv")
max_eco_footprint = eco_footprints["Ecological footprint"].max()
political_countries_url = (
"http://geojson.xyz/naturalearth-3.3.0/ne_50m_admin_0_countries.geojson"
)
m = folium.Map(location=(30, 10), zoom_start=3, tiles="cartodb positron")
folium.Choropleth(
geo_data=political_countries_url,
knowledge=eco_footprints,
columns=("Nation/area", "Ecological footprint"),
key_on="function.properties.title",
bins=(0, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, max_eco_footprint),
fill_color="RdYlGn_r",
fill_opacity=0.8,
line_opacity=0.3,
nan_fill_color="white",
legend_name="Ecological footprint per capita",
title="International locations by ecological footprint per capita",
).add_to(m)
folium.LayerControl().add_to(m)
m.save("footprint.html")
These two extra traces of code additional enhance the usability of your map by giving the choropleth map layer a descriptive title and permitting your viewers to toggle it:
Your map appears to be like nice and resembles the Wikipedia map that’s primarily based on the identical knowledge. What’s even higher is that your map is interactive and permits viewers to zoom and transfer with out the necessity so that you can code that performance your self. Since you added the LayerControl
factor, they’ll now even toggle the choropleth layer seamlessly.
Nonetheless, the map isn’t good. There’s room for enchancment in each knowledge and design. If you wish to practice your knowledge visualization abilities, pay attention to the potential points that you can imagine with the map in its present state. Then, learn on for some enchancment strategies.
Subsequent Steps
The map that you just constructed appears to be like good, and whereas constructing it, you labored with a number of totally different elements of Folium. Nonetheless, you may need found some points with the ultimate map.
One potential challenge together with your map is what areas you show as political items. Folks all over the world might have totally different opinions on what areas ought to be thought of separate political international locations, or the place to attract the borders. Whenever you construct a map, you may need to query your assumptions and what worldview you propagate together with your map design.
One other challenge is that a number of international locations present up as lacking values in your map despite the fact that there’s knowledge for a few of these international locations in your CSV file. In these circumstances, linking the GeoJSON nation function and the row data out of your CSV file didn’t work out.
Be aware: The linking failures are most certainly as a result of two datasets’ spelling a rustic title in another way. For instance, whereas the Czech Republic is famous as Czech Republic within the CSV file, it exhibits up as Czech Rep. beneath function.properties.title
within the GeoJSON knowledge.
You may attempt to key the 2 datasets on a unique property of the nation options, however you’ll most likely discover that this simply strikes the difficulty from some international locations to different international locations. Information is rarely utterly clear, so that you would possibly as a substitute wish to look into cleaning your data with pandas earlier than linking it to your GeoJSON options.
The bin colours additionally go away room for enchancment. When you’ve ran into the constraints of what you are able to do by passing parameters in Choropleth
, you possibly can apply much more type customization on a GeoJson
object by utilizing style_function()
. Are you able to edit your code in order that the ensuing map resembles the one on Wikipedia much more carefully?
Lastly, in the event you’re performed with this map undertaking however wish to be taught extra about utilizing Folium on your subsequent undertaking, then you possibly can find out about including markers to your Folium maps. As soon as about markers, you possibly can build a location-based web app with Django and GeoDjango and present the places on an online map utilizing Folium.
Conclusion
Properly performed making it to the tip of this tutorial! You constructed a choropleth map utilizing Python’s Folium library. On the similar time, you skilled your knowledge visualization abilities and added Folium as a brand new device to your device belt.
On this tutorial, you’ve discovered methods to:
- Create an interactive map utilizing Folium and reserve it as an HTML file
- Select from totally different internet map tiles
- Anchor your map to a particular geolocation
- Bind knowledge to a GeoJSON layer to create a choropleth map
- Fashion the choropleth map
When you’re working with knowledge that has a geographical part, then attempt to use Folium to visualise it and acquire extra insights. Moreover, you possibly can create a report that your colleagues and the Web will wish to take a look at and which you could share as a static web site.
Did you want utilizing Folium to visualise your knowledge? Did you’re employed with a unique dataset? What options of the library would you wish to be taught extra about? Depart a observe within the feedback beneath and carry on mapping!
Take the Quiz: Take a look at your information with our interactive “Python Folium: Create Net Maps From Your Information” quiz. Upon completion you’ll obtain a rating so you possibly can observe your studying progress over time: