添加下拉菜单以绘制树形图

Son*_*on6 3 python treemap drop-down-menu plotly plotly-express

我目前正在尝试向我的树状图添加下拉菜单

我正在使用的代码:

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()
Run Code Online (Sandbox Code Playgroud)

我面临的问题是,在我的“RuleName”列中,我有 151 个不同的值(但总共 1300 行),这就是为什么我尝试添加一个按钮,允许自己选择要绘制树形图的 RuleName 值。现在我正在使用一种野蛮的方法,即通过每个 RuleName 值过滤我的数据帧,这导致我获得 151 个不同的树形图。我在该网站或任何其他网站上找不到任何解决方案。

感谢您的帮助

rpa*_*nai 7

在这里,我基本上使用与此答案相同的逻辑,但我用来px.treemap(...).data[0]生成跟踪而不是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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述