简体   繁体   中英

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-

在此处输入图像描述

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM