Search code examples
pythonplotlycolorbarplotly-pythonchoropleth

Plotly Express: Make colorbar static in animation


There is a similar question here but the solution is not working for me. Maybe it's because I am generating the map via px rather than go.

I am trying to make the colorbar static, but I am not able to achieve that properly. I added z, zmax and zmin to the traces but it results in weird behaviour. In the provided example here, it makes the entire map static. (in my original dataframe, it shows false values on some countries) What am I doing wrong here, any guidance would be appreciated.

import plotly.express as px

df = px.data.gapminder()

fig = px.choropleth(df, locations='iso_alpha', color='gdpPercap', animation_frame=df.year.astype(str),
                        projection ='equirectangular')
    
# fig.update_traces(z=df['lifeExp'],zmin=0, zmax=100)
# for idx,frame in enumerate(fig.frames):
#     frame.data[0].update(z=df['lifeExp'], zmin=0, zmax=100)
fig.show()

enter image description here


Solution

  • Oh well, adding range_color to the main function call and specifying the range (min,max) does the trick here. I used the min and max of the gdpPercap feature itself, but they other values can be used too.

    import plotly.express as px
    
    df = px.data.gapminder()
    
    fig = px.choropleth(df, locations='iso_alpha', color='gdpPercap', animation_frame=df.year.astype(str),
                            projection ='equirectangular', range_color=(min(df.gdpPercap), max(df.gdpPercap)))
    fig.show()
    

    enter image description here