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
- Go to https://www.mapbox.com/ and click on sign up.
- Verify your e-mail address.
- Now, click on “tokens” in the navbar.
- Copy your Default Public Token and paste it into your notepad.
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).
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
# url = "https://gist.githubusercontent.com/ jbrobst/ # 56c13bbbf9d97d187fea01ca62ea5112/raw/ # e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson" with urlopen(url) as response: body = response.read() geo_json = json.loads(body) # geo_json |
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
# Paste the file path of your CSV file here 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
# paste you token that you copied from mapbox 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(): #print(k,v) 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_style="carto-positron", 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.