How to make Choropleth Maps with Labels using Mapbox API
Last Updated :
04 Sep, 2022
Choropleth maps are interesting visualization tools that use the intensity of a color to represent aggregate data for different locations within their bounding boxes. They are a lot of fun and are fairly easy to make using the Plotly library. Choropleth maps are powerful data visual representations of data. Let’s get started with a step-by-step guide:
Set Up Your Mapbox Account

Fig. 2 Mapbox account after logging in.
Find an Appropriate GeoJson File for Your Map
If you perform a simple google search typing “{desired map} geojson file”, chances are, that you’ll find the GeoJson file you’re looking for. In this case, we are using the GeoJson file of the Indian State-Wise Map. (you can find it here).
Picking a Suitable Dataset
For this example, we’re using the Indian map and our aim is to divide the map into its state-wise components. For the aforementioned reasons, we’ll have to pick a dataset such that it has a value corresponding to each of India’s states and union territories. Hence, we’ve created a CSV File of data pertaining to Alcohol Consumption Percentage Per State in India. (you can find the dataset on https://www.findeasy.in/alcohol-consumption-in-india/ or you can simply download the CSV file from here).

Fig. 3 CSV file of the appropriate dataset
Step 1:
Import these libraries, necessary to make our code work:
Python3
from urllib.request import urlopen
import json
import pandas as pd
from shapely.geometry import shape
import plotly.graph_objects as go
import plotly.express as px
|
Step 2:
Now load your geojson file using json.load().
Python3
with urlopen(url) as response:
body = response.read()
geo_json = json.loads(body)
|
Output:
{‘type’: ‘FeatureCollection’,
‘features’: [{‘type’: ‘Feature’,
‘geometry’: {‘type’: ‘Polygon’,
‘coordinates’: [[[95.23391968067268, 26.68245856965871],
[95.23282005383173, 26.705791937482644],
[95.21038086477148, 26.73124215303452],…
Step 3:
Pass the data from your CSV file to a Pandas’s Dataframe.
Python3
df = pd.read_csv( "D:\Documents\india_alcohol_stats.csv" )
df.head()
|
Output:
state consumption
0 Andaman & Nicobar 25.4
1 Andhra Pradesh 13.7
2 Arunachal Pradesh 28.0
3 Assam 8.8
4 Bihar 7.9
Step 4:
Place your dataset in your geojson file.
Note: In place of “ST_NM”, you can write the name of the equivalent field by looking at your geojson file.
Python3
center_pos = {}
features = geo_json[ 'features' ]
for feature in features:
k = feature[ 'properties' ][ 'ST_NM' ]
s = shape(feature[ "geometry" ])
p = s.centroid
center_pos[k] = list (p.coords)
|
Step 5:
Save your MAPBOX token in a variable.
Python3
mapbox_access_token = "{YOUR_TOKEN_KEY_HERE}"
|
Step 6:
Add this code snippet to customize what your labels will look like. Customize the “val” fields in accordance with your CSV file.
Note: In the above code, we have chosen all the labels above the 26% mark to be of white color and the rest in black because darker color labels go with light colored background and so on.
Python3
fig = go.Figure()
for k,v in center_pos.items():
val = df[df[ 'state' ] = = k][ 'consumption' ]
try :
if float ( format (val.values[ 0 ]))> 26.0 :
colour = 'white'
else :
colour = 'black'
val = format (val.values[ 0 ]) + '%'
except IndexError:
val = '{:1}' . format ( 1 )
fig.add_trace(go.Scattermapbox(
lat = [center_pos[k][ 0 ][ 1 ]],
lon = [center_pos[k][ 0 ][ 0 ]],
mode = 'text' ,
textfont = dict (
color = colour,
size = 12 ,
),
text = val,
showlegend = False
))
|
Step 7:
Finally, add the following code which will help us display our data on the map. For your map, you can choose one of these colorscales.
Python3
fig.add_trace(go.Choroplethmapbox(
geojson = geo_json,
locations = df[ 'state' ],
featureidkey = "properties.ST_NM" ,
z = df[ 'consumption' ],
colorscale = "Blues" ,
marker_opacity = 0.7 ,
marker_line_width = 0
))
fig.update_layout(
mapbox_accesstoken = mapbox_access_token,
mapbox_zoom = 4 ,
mapbox_center = { "lat" : 22.5 , "lon" : 81.0 }
)
fig.update_layout(autosize = False ,
height = 600 ,
width = 800 ,
margin = { "r" : 0 , "t" : 0 , "l" : 0 , "b" : 0 },
)
fig.show()
|
Step 5: Download Your Map
If you find any white-colored state (i.e. 0% in the label), consider checking your CSV file again for the correct state name and data. you can download the map by right-clicking on the camera icon on the top right of the map.

Fig. 1 Transposing data on a map with labels using Mapbox
Similar Reads
How to make a choropleth map with a slider using Plotly in Python?
Choropleth Map is a type of thematic map in which a set of pre-defined areas is colored or patterned in proportion to a statistical variable that represents an aggregate summary of a geographic characteristic within each area. Choropleth maps provide an easy way to visualize how a variable varies ac
2 min read
Animated choropleth map with discrete colors using Python plotly
Animated Choropleth Maps can be implemented by Python Plotly. This map is can be composed of colored polygons. We can easily represent spatial variations of any quantity with the help of choropleth maps. To make choropleth maps some basic inputs are required Geometrical/regional Information: This ty
3 min read
How to re-size Choropleth maps - Python
In this article, we are going to learn how to create resizable maps using different libraries in Python. Choropleth maps are a type of thematic map that displays divided regions or territories shaded or patterned in relation to a specific data variable. In Python, choropleth maps can be created usin
3 min read
Choropleth Maps using Plotly in Python
Plotly is a Python library that is very popular among data scientists to create interactive data visualizations. One of the visualizations available in Plotly is Choropleth Maps. Choropleth maps are used to plot maps with shaded or patterned areas which are proportional to a statistical variable. Th
3 min read
Python Plotly - How to set colorbar position for a choropleth map?
In this article, we will learn how to set colorbar position for a choropleth map in Python using Plotly. Color bar are gradients that go from bright to dark or the other way round. They are great for visualizing data that go from low to high, like income, temperature, or age. Choropleth maps are use
2 min read
Plotting Data on Google Map using Python's pygmaps package
pygmaps is a matplotlib-like interface to generate the HTML and javascript to render all the data users would like on top of Google Maps. Command to install pygmaps : pip install pygmaps (on windows)sudo pip3 install pygmaps (on linix / unix)Code #1 : To create a Base Map. [GFGTABS] Python # import
3 min read
Python | Plotting Google Map using folium package
Folium is built on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet.js (JavaScript) library. Simply, manipulate your data in Python, then visualize it on a leaflet map via Folium. Folium makes it easy to visualize data that's been manipulated in Python, o
2 min read
Python | Plotting Google Map using gmplot package
gmplot is a matplotlib-like interface to generate the HTML and javascript to render all the data user would like on top of Google Maps. Command to install gmplot : pip install gmplotCode #1 : To create a Base Map [GFGTABS] Python # import gmplot package import gmplot # GoogleMapPlotter return Map ob
2 min read
plotly.figure_factory.create_choropleth() function in Python
Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. plotly.figure_factory.create_choropleth A Choropleth Map is a map composed of colored polygons. It is used to represent spatial variations of a quantity. Syntax: plotly.figure_factory.cre
1 min read
Treemap using graph_objects class in plotly
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library
2 min read