Plotly:仅在子节点的树图中显示悬停信息 [英] 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-
可见,它正确显示了 USA
和所有其他子节点的 total_cases_per_100
值.但是对于父节点,它会加起来,这是错误的,因为 total_cases_per_100
是一个比率而不是总数.
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.
无论如何我可以隐藏除子节点之外的所有节点的 value
悬停信息吗?
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.
推荐答案
您可以使用 hover_data
/customdata
并覆盖非叶节点的值.
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
这篇关于Plotly:仅在子节点的树图中显示悬停信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!