How to make a choropleth map with a slider using Plotly in Python?
Last Updated :
21 Feb, 2022
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 across a geographic area or show the level of variability within a region.
Sliders can be used in plotly to change the data displayed or the style of a plot. It is a handy tool that can be used to display changes in a choropleth map.
Installation
Let’s start by installing plotly:
pip install plotly
Now, let’s Import the necessary libraries.
Python3
import pandas as pd
import plotly
import numpy as np
|
Loading Dataset
Loading sample dataset. We’ll use this dataset to plot a choropleth map.
Python3
df = pd.read_csv('https: / / raw.githubusercontent\
.com / plotly / datasets / master / 2011_us_ag_exports .csv')
data = [ dict ( type = 'choropleth' ,
locations = df[ 'code' ].astype( str ),
z = df[ 'total exports' ].astype( float ),
locationmode = 'USA-states' )]
|
Creating Slider
Now, let’s build our slider:
Python3
steps = []
for i in range ( len (data)):
step = dict (method = 'restyle' ,
args = [ 'visible' , [ False ] * len (data)],
label = 'Year {}' . format (i + 1980 ))
step[ 'args' ][ 1 ][i] = True
steps.append(step)
sliders = [ dict (active = 0 , pad = { "t" : 1 }, steps = steps)]
|
Final Code with Output
Finally, let’s put all the code together and plot the choropleth map with a slider.
Python3
import pandas as pd
import plotly
import numpy as np
plotly.offline.init_notebook_mode()
df = pd.read_csv('https: / / raw.githubusercontent.\
com / plotly / datasets / master / 2011_us_ag_exports .csv')
data = [ dict ( type = 'choropleth' ,
locations = df[ 'code' ].astype( str ),
z = df[ 'total exports' ].astype( float ),
locationmode = 'USA-states' )]
for i in range ( 5 ):
data.append(data[ 0 ].copy())
data[ - 1 ][ 'z' ] = data[ 0 ][ 'z' ] * np.random.rand( * data[ 0 ][ 'z' ].shape)
steps = []
for i in range ( len (data)):
step = dict (method = 'restyle' ,
args = [ 'visible' , [ False ] * len (data)],
label = 'Year {}' . format (i + 1980 ))
step[ 'args' ][ 1 ][i] = True
steps.append(step)
slider = [ dict (active = 0 ,
pad = { "t" : 1 },
steps = steps)]
layout = dict (geo = dict (scope = 'usa' ,
projection = { 'type' : 'albers usa' }),
sliders = slider)
fig = dict (data = data,
layout = layout)
plotly.offline.iplot(fig)
|
Output:
Share your thoughts in the comments
Please Login to comment...