Search code examples
pythonplotlydata-visualizationtreemapplotly-python

Plotly: Show hoverinfo in treemap only for child nodes


import pandas as pd
import plotly.express as px

df = pd.DataFrame({'world':['world']*4,
                   'continent':['SA','SA','NA','NA'],
                  'country':['Brazil','Uruguay','USA','Canada'],
                  'total_cases_per_100':[6,1,12,8]})

fig = px.treemap(df, path=['world','continent','country'],values='total_cases_per_100')
fig.update_traces(hovertemplate=None, hoverinfo='value')

The code above gives the following output-

enter image description here

As visible, it displays correctly the value of total_cases_per_100 for USA and all the other child nodes. But for parent nodes, it sums it up, which is wrong as total_cases_per_100 is a ratio and not a total.

Is there anyway I can hide the value hoverinfo for all nodes except the children?

In case this is not possible, the actual value for the parent nodes is also available with me but I am not sure how I could replace the generated value with it.


Solution

  • You can use hover_data / customdata and override values for none leaf nodes.

    import pandas as pd
    import plotly.express as px
    
    
    df = pd.DataFrame({'world':['world']*4,
                       'continent':['SA','SA','NA','NA'],
                      'country':['Brazil','Uruguay','USA','Canada'],
                      'total_cases_per_100':[6,1,12,8]})
    leaves = df.select_dtypes("object").apply("/".join, axis=1).values
    
    
    fig = px.treemap(df, path=['world','continent','country'],values='total_cases_per_100', hover_data=["total_cases_per_100"])
    fig.update_traces(hovertemplate='%{customdata[0]}')
    fig.data[0].customdata = [
        v if fig.data[0].ids[i]
        in leaves else [""]
        for i, v in enumerate(fig.data[0].customdata)
    ]
    fig