Search code examples
pythonplotlytreemap

Change max/min value colorbar in treemap


This is an example treemap chart from plotly library

import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")

print(np.average(df['lifeExp'], weights=df['pop']))
fig = px.treemap(df, path=[px.Constant("world"), 'continent', 'country'], values='pop',
                  color='lifeExp', hover_data=['iso_alpha'],
                  color_continuous_scale='RdBu',
                  color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop'])
                )
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
fig.show()

These values should be min = 0 and max = 200 as below. Could you help me? enter image description here


Solution

  • According to the plotly express treemap documentation, you can pass a list [min,max] to the range_color argument:

    import plotly.express as px
    import numpy as np
    df = px.data.gapminder().query("year == 2007")
    
    print(np.average(df['lifeExp'], weights=df['pop']))
    fig = px.treemap(df, path=[px.Constant("world"), 'continent', 'country'], values='pop',
                      color='lifeExp', hover_data=['iso_alpha'],
                      color_continuous_scale='RdBu',
                      color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']),
                      range_color=[0,200]
                    )
    fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
    fig.show()
    

    enter image description here