简体   繁体   English

Plotly:仅在树形图中为子节点显示 hoverinfo

[英]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.可见,它正确显示了USA和所有其他子节点的total_cases_per_100的值。 But for parent nodes, it sums it up, which is wrong as total_cases_per_100 is a ratio and not a total.但是对于父节点,它总结了它,这是错误的,因为total_cases_per_100是一个比率而不是总数。

Is there anyway I can hide the value hoverinfo for all nodes except the children?无论如何我可以隐藏除子节点以外的所有节点的value hoverinfo 吗?

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.您可以使用hover_data / customdata并覆盖非叶节点的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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