Search code examples
pythonplotlyplotly-pythonplotly-express

Change hover text of a plotly express treemap


I want to show in a treemap just the label and value of each item, not parent or ID. I have defined it with plotly express. No matter how much I have tinkered with it, I haven’t been able to restrict hover text to the fields I need. Check the code and capture

import plotly.express as px

fig = px.treemap(dfconcepto, path=['type','name'], 
                 values = 'count',
                 width=900, height=900,
                 hover_data = ['count'],
)

fig.show()

image
image
1117×957 44.9 KB I also have tried to create it with non-express treemap. Hovertext is what I want, but then a treemap with two levels is rendered asymmetric.

enter image description here

What I want is something like the hovertext of non-express treemap, but balanced and symmetric as in express treemap

What can I do?

Thanks in advance!


Solution

  • It seems to me you should overwrite your hover template

    import pandas as pd
    import plotly.express as px
    url = "https://gist.githubusercontent.com/jlchulilla/3b4e40f68ba73b5dbcb661a1d861f308/raw/e564973db30a4612aba60c5b26dd108edc98f048/test2sof.csv"
    
    df = pd.read_csv(url).drop("Unnamed: 0", axis=1)
    
    fig = px.treemap(df, path=['type','name'], 
                     values = 'coincidencia',
                     width=900, height=900,
    )
    
    # Now your hovertemplate looks like
    # fig.data[0].hovertemplate 
    # 'labels=%{label}<br>coincidencia=%{value}<br>parent=%{parent}<br>id=%{id}<extra></extra>'
    
    # But it seems to me you want something like
    fig.data[0].hovertemplate = '%{label}<br>%{value}'
    fig.show()