Python plotly: how to make a choropleth map with a slider (access grid data issue)

I want to draw a choropleth world map with a slider for the year values. It would be a combination of the “Choropleth Map” and the “Adding Sliders to Animations” (https://plot.ly/python/).

First I searched plotly’s community forum and the web for an example of a plotly choropleth map with grid data or a slider without success.

While I managed to replicate the slider animation example with my data (see jupyter notebook link below), adapting the choropleth code to access grid data with a slider does not seem to work.

In contrast to a regular map (like in example one), data is not loaded from a dataframe column but is uploaded to a plotly grid. In example two we can see that instead of regular x,y and text values in the data_dict, xsrc, ysrc and textsrc are used to access the grid data.

data_dict = {
       'xsrc': grid.get_column_reference(col_name_template.format(
            year=year, continent=continent, header='lifeExp'
        )),
        'ysrc': grid.get_column_reference(col_name_template.format(
            year=year, continent=continent, header='gdpPercap'
        )),

Chloropleth maps are defined in plotly by setting locations, z-values and text values in list form. In order to check if plotly choropleth maps support grid data, I searched in the api-documentation and found equivalents: locationsrc, zsrc, and textsrc. Therefore using grid data should be possible. When I draw my adapted graph though, I see only the coastline and the slider but no countries being highlighted.

A jupyter notebook with code and data with additional links can be found here: https://github.com/MathiasRiechert/plolty-choropleth-slider-notebook/blob/master/choropleth-slider-notebook.ipynb

Unfortunately, I can’t find a way to debug why nothing is shown in the map. Is there a way to debug why nothing is shown on the plotly website? What else reasons might cause that nothing is shown?Preformatted text

@mathias.riechert I inspected the code here: https://plot.ly/~mathias.riechert/72/#code and noticed that in the definition of each choropleth, to z is assigned an empty list, or z must be a list of numerical values.

1 Like

@mathias.riechert - were you able to workout how to do this?

I did not find time for it until now, will not have time for this before July, so taking the code from GitHub and modifying it yourself might be the faster approach.

Has anybody solved this problem? Any help would be highly appreciated!

Hi @KilgoreTrout I was able to put a time series slider on a choropleth map. Let me know if you still need a solution. Cheers

I would like that if you have it

Here’s a solution that worked out using Dash:

https://opioid-epidemic.herokuapp.com/

Python code for this:

1 Like

i read the article intro to animations, and tried to create a choropleth map with slide and animation based on month_year.
I was able to replicate the codes at the end of this website. https://plot.ly/python/animations/
I feel i did everything right. at the end, there is play and stop button, there is a choropleth map, there is a slider. Everything looked right until i hit play button. the slider automatically moves, however, my map color does not change. It stays at the initial value. which is 2019-04. when i hover over, there is no hovertext either. (there is hover text before i hit play button)
can you please help me? Thank you.
available_timeline_list=[‘2019-04’,‘2019-03’,‘2019-02’,‘2019-01’]

make figure

fig_dict = {
“data”: [],
“layout”: {},
“frames”: []
}

fill in most of layout

fig_dict[“layout”][“hovermode”] = “closest”
fig_dict[“layout”][“sliders”] = {
“args”: [
“transition”, {
“duration”: 400,
“easing”: “cubic-in-out”
}
],
“initialValue”: “2019-04”,
“plotlycommand”: “animate”,
“values”: available_timeline_list,
“visible”: True
}
fig_dict[“layout”][“updatemenus”] = [
{
“buttons”: [
{
“args”: [None, {“frame”: {“duration”: 500, “redraw”: False},
“fromcurrent”: True, “transition”: {“duration”: 300,
“easing”: “quadratic-in-out”}}],
“label”: “Play”,
“method”: “animate”
},
{
“args”: [[None], {“frame”: {“duration”: 0, “redraw”: False},
“mode”: “immediate”,
“transition”: {“duration”: 0}}],
“label”: “Pause”,
“method”: “animate”
}
],
“direction”: “left”,
“pad”: {“r”: 10, “t”: 87},
“showactive”: False,
“type”: “buttons”,
“x”: 0.1,
“xanchor”: “right”,
“y”: 0,
“yanchor”: “top”
}
]

sliders_dict = {
“active”: 0,
“yanchor”: “top”,
“xanchor”: “left”,
“currentvalue”: {
“font”: {“size”: 20},
“prefix”: “Year:”,
“visible”: True,
“xanchor”: “right”
},
“transition”: {“duration”: 300, “easing”: “cubic-in-out”},
“pad”: {“b”: 10, “t”: 50},
“len”: 0.9,
“x”: 0.1,
“y”: 0,
“steps”: []
}

make data

year = ‘2019-04’
df_state_selected_date = df_state_[df_state_[“month_year”] == year]
data_dict = {
“type”: “choropleth”,
“locations”: list(df_state_selected_date[‘state_abbr’]),
“z”: list(df_state_selected_date['Cumulative '].astype(float)),
“zmin”: 0,
“zmax” :80000,
“locationmode”: “USA-states”,
“text”: list(df_state_selected_date[‘state’]),
“colorscale”:“Greens”,
“colorbar_title”:“aaa
bbb”,
“colorbar”:dict(thickness=25, thicknessmode=‘pixels’, len=0.6, lenmode=‘fraction’)
}
fig_dict[“data”].append(data_dict)
fig_dict[“layout”][“geo_scope”]=‘usa’

make frames

for year in available_timeline_list:
frame = {“data”: [], “name”: year}
df_state_selected_date = df_state_[df_state_[“month_year”] == year]
data_dict = {
“type”: “choropleth”,
“locations”: list(df_state_selected_date[‘state_abbr’]),
“z”: list(df_state_selected_date['Cumulative '].astype(float)),
“zmin”: 0,
“zmax” :80000,
“locationmode”: “USA-states”,
“text”: list(df_state_selected_date[‘state’]),
“colorscale”:“Greens”,
“colorbar_title”:“aaa
bbb”,
“colorbar”:dict(thickness=25, thicknessmode=‘pixels’, len=0.6, lenmode=‘fraction’)
}
frame[“data”].append(data_dict)
fig_dict[“frames”].append(frame)

print(fig_dict)

slider_step = {"args": [
[year],
{"frame": {"duration": 300, "redraw": False},
 "mode": "immediate",
 "transition": {"duration": 300}}],
"label": year,
"method": "animate"}
sliders_dict["steps"].append(slider_step)

fig_dict[“layout”][“sliders”] = [sliders_dict]

fig = go.Figure(fig_dict)
fig.show()

Good and bad news! my codes above actually works. It is just very slow that the map does not have enough time to reload. I read in dash plotly Java section, although i am writing in python, other than scatter and bar chart, other animation is not smooth at all.