Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add dropdown menu to plotly express treemap

I am currently trying to add a dropdown menu to my treemap plot

The code I am using :

import pandas as pd
import plotly.express as px

fig = px.treemap(df, 
                 path=['RuleName','RuleNumber','ParaInvolved',"CreationP","MAjP"],
                 color='Somme',
                 hover_data=["RuleDecision","RuleMAJ"],
                 color_continuous_scale='RdBu')
    
fig.show()

The problem I am facing is that in my column "RuleName" I have 151 different values (but 1300 rows in total), that's why I'm trying to add a button allowing myself to chose for what RuleName value I want to plot my treemap. For now I am using a barbaric method consisting in filtering my dataframe by each RuleName value, which lead me to get 151 different treemap. I don't find any solution on that website or any other.

Thanks for your help

like image 911
Son6 Avatar asked Dec 29 '25 12:12

Son6


1 Answers

Here I'm basically using the same logic from this answer but I use px.treemap(...).data[0] to produce the traces instead of go.

import plotly.express as px
import plotly.graph_objects as go
df = px.data.tips()

# We have a list for every day
# In your case will be gropuby('RuleName')
# here for every element d
# d[0] is the name(key) and d[1] is the dataframe
dfs = list(df.groupby("day"))

first_title = dfs[0][0]
traces = []
buttons = []
for i,d in enumerate(dfs):
    visible = [False] * len(dfs)
    visible[i] = True
    name = d[0]
    traces.append(
        px.treemap(d[1],
                   path=['day', 'time', 'sex'],
                   values='total_bill').update_traces(visible=True if i==0 else False).data[0]
    )
    buttons.append(dict(label=name,
                        method="update",
                        args=[{"visible":visible},
                              {"title":f"{name}"}]))

updatemenus = [{'active':0, "buttons":buttons}]

fig = go.Figure(data=traces,
                 layout=dict(updatemenus=updatemenus))
fig.update_layout(title=first_title, title_x=0.5)
fig.show()

enter image description here

like image 61
rpanai Avatar answered Jan 01 '26 01:01

rpanai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!