This post will introduce how to visualize the continuous variable on the map with the use of choropleth_mapbox, a mighty tool to realize animation.

Table of Contents

  1. Step 1. import all needed packages
  2. Step 2. import json file from existing file
  3. Step 3. make the json file smaller
  4. Step 4. Visualization through choropleth_mapbox
  5. Step 5. Export the image as local html
  6. Step 6. Save the image on plotly account

Step 1. import all needed packages

1
2
3
4
5
6
7
8
9
10
11
import numpy as np
import pandas as pd

import chart_studio.plotly as py
import plotly.tools as tls
import plotly.express as px

import json

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

Step 2. import json file from existing file

The .json file could be converted from shp. file. I convert it directly by using QGIS.

More conveniently, you can use package shapefile in python to finish the conversion. Check reference for more detail.

1
2
3
4
with open('Simplify_GeoJSON_CHNcity.json') as f:
CHN_cities = json.load(f)
# below is the alternative to load the json file
# CHN_cities = json.load(open("GeoJSON_CHNcity.geojson","r"))
1
2
3
4
# examine the fearue of the json file
CHN_cities["features"][0].keys()
CHN_cities["features"][0]["properties"]
CHN_cities["features"][0]

{‘type’: ‘Feature’,
‘geometry’: {‘type’: ‘Polygon’,
‘coordinates’: [[[116.12962341, 29.82485008],
[116.27577972, 29.79137039],
[116.4651413, 29.90048981],
[116.54703522, 29.9179039],
[116.58567047, 30.05631828],…

You could find out that the coordinates is in 8 decimal places, which will inflate the size of the map. Therefore, we need the following step.

Step 3. make the json file smaller

  • First, check If you have large GeoJSON files, such as over 20 or 30 MB. The map upload tends to be slow. And normally could not be uploaded to plotly account.

  • The easiest way is to use https://mapshaper.org/ to simplify the json file, to make the json file better less than 3MB. You would not lose necessary information because we here care about various coloration across regions.

  • When you have already finish above two steps, your json file is already small enough. To make it even smaller, run following code to shrink it 10% or so.

1
2
3
4
5
6
7
8
9
10
#Round off the locations to 2 decimal places (about 1.1 km accuracy)
for i in range(0, len(CHN_cities["features"])):
for j in range(0,len(CHN_cities["features"][i]['geometry']['coordinates'])):
try:
CHN_cities["features"][i]['geometry']['coordinates'][j] = np.round(np.array(CHN_cities["features"][i]['geometry']['coordinates'][j]),2)
except:
print(i,j)

# If you now check the coordinates again, you’ll see that they have been rounded off to 2 decimal places:
CHN_cities["features"][0]['geometry']['coordinates'][0][0]

array([116.13, 29.82])

Step 4. Visualization through choropleth_mapbox

1
2
3
4
5
6
7
8
9
10
11
12
13
fig_Heterogeneity = px.choropleth_mapbox(df_EC, 
locations = "id",
geojson = CHN_cities,
color = "EC",
mapbox_style="carto-positron", # carto-darkmatter",
opacity = 0.8,color_continuous_midpoint = 0,zoom = 2.5,
color_continuous_scale = px.colors.diverging.balance,
labels={'EC':'Environmental Heterogeneity'},
center={"lat": 38, "lon": 104},
range_color=(-2.5, 1.8) )
# zoom = 3, )
fig_Heterogeneity.update_layout(margin={"r":0,"t":0,"l":0,"b":0},height = 380, width = 759)
fig_Heterogeneity.show()

In the default browser, we get the following image, indicating the environmental complexity across China.

Environmental Heterogeneity

Step 5. Export the image as local html

You might want it.. Even though I don’t think it’s that useful

1
2
import plotly.io as pio
pio.write_html(fig_Heterogeneity, file='figure.html', auto_open=True)

Step 6. Save the image on plotly account

1
py.plot(fig_Heterogeneity, filename = 'Environmental Heterogeneity', auto_open=True)

It uploads the image online including the data on your plotly account.

If returned with the following error!! Go back to step 3 to shrink the size.

“This file is too big! Your current subscription is limited to 524.288 KB uploads. For more information, please visit: https://plotly.com/get-pricing/."

Cheers!🥳

The following image depicts the environmental dispersion across China. Same steps above can get you this beautiful visualization.

Environmental Dispersion

References:

https://medium.com/tech-carnot/plotly-mapbox-interactive-choropleth-visualization-tutorial-957dcdbca90b