Skip to content
Advertisement

Callback from sunburst chart. DASH PLOTLY

i’m writing a code with a sunburst chart that will present all classes from some type of data, and when the user click on what class he wanna see my dropdown menu should present values only from that classe.

So, my difficult where how to do this callback, cause all the ways that i tried failed.

my df used look like this

df = {'Nome': ['Aberdeen Multi Asset Growth Advisory FIM IE',
'Absolute Alpha Global Advisory FIC FIM',
'Absolute Alpha Marb Advisory FIC FIM',
'Absolute Hedge FIC FIM',
'Claritas Hedge Advisory FIC FIM Longo Prazo',
'MOS Institucional FIA',
'Occam Long Biased Advisory FIC FIM',
'Sharp Equity Value Advisory FIC FIA',
'Vinland Macro Advisory FIC FIM'],

'tipo':['Internacional Multimercado Hedgeado',
'Multiestratégia',
'Internacional Multimercado Hedgeado',
'Macro Média Vol',
'Macro Média Vol',
'Renda Variável Long Only',
'Renda Variável Long Biased',
'Renda Variável Long Only',
'Macro Média Vol',
],


'retorno 1 mês':[ '0,79%',
'0,38%',
'0,40%',
'0,38%',
'0,82%',
'4,11%',
'4,02%',
'4,55%',
'0,72%'],

'classes' :
[
'Internacional Multimercado Hedgeado',
'Multiestratégia',
'Macro Média Vol',
'Renda Variável Long Only',
'Renda Variável Long Biased',
'Macro Alta Vol',
'Quantitativo',
'Long Short Direcional',
'Long Short Neutro'],

'número de fundos':
['8',
'6',
'10',
'59',
'37',
'30',
'10',
'15',
'11'
]



}

df = pd.DataFrame(df)
app = Dash(__name__, external_stylesheets= [dbc.themes.DARKLY])


app.layout = dbc.Container(

    dbc.Row([
        dbc.Col([
#First Div, where objective of dashboard be presented
#This piece also include our logo on left side
#Few personalization options, simple template
            html.Div([
                html.Img(id='logo_png', src=app.get_asset_url("logo.png"), height= 50
                ),               
                html.H5("Os fundos que acompanhamos estão dividos nas seguintes abaixo"
                ),
#Phrase below our pie chart
            html.P('Selecione a classe que deseja obter mais informações'
            ),
#Pie chart id created inside this .Div
            html.Div([                 
                    dcc.Graph(id = 'pie_class_chart', figure = {},
                    style={'width': '100%', 'display': 'inline-block', 'vertical-align': 'right', })                
            ]),
        dbc.Col(
            html.Div([
                dash_table.DataTable(
                    id = 'tabela-dash',
                    columns = [{"id": i, "name": i} for i in dff.columns],
                    data= dff.to_dict('records'),
                    style_table={'height': '510px', 'overflowY': 'auto', 'display': 'inline-block', 'vertical-align':'left', 'float': 'left'},
                    style_data={
                    'color': 'black',
                  'backgroundColor': 'white'},
                  page_size= 15
                )
            ]),
        ),
#Dropdown of funds classification
#Dropdown-value is the id necessary to insert possible values inside what we want
#  
            html.Div(id="fund_class_selector", children=[                
                html.P('Selecione abaixo o fundo para o qual deseja obter mais informações'
                ),       
                dcc.Dropdown(df['Nome'].unique(), id= 'dropdown-value')],                
                ) 
            ]),
#Options of windowns, with click buttons                      
        ]),        
     ]),
)

####INTERACTIVE FUNCTIONS ARE BELOW######

######

#Callback of first chart

@app.callback(
    Output(component_id='pie_class_chart', component_property= 'figure'),    
    Input(component_id='tabela-dash', component_property='data'))        

def update_graph(fund_class):
    fig = px.pie(df, values = 'número de fundos', names = 'tipo', title = 'Teste' )
    return fig

  


#callback of datatable values
@app.callback(
    Output(component_id="dropdown-value", component_property='options'),
    Input(component_id = 'pie_class_chart', component_property='clickData'))


def display_click_data(clickData):
    try:
        value = clickData['points'][0]['label']
        dcc.Dropdown(dff[dff['type'] == value]['type'])
        return dcc.Dropdown

    except:
        print('error')



if __name__ == '__main__':
    app.run_server(debug=True, use_reloader=False )


Advertisement

Answer

You can try to use this code below:

Full example:

import dash
import dash_bootstrap_components as dbc
from dash import Dash, html, dcc,dash_table
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd

# dff_dict = ..... add here the dictionary 
dff = pd.DataFrame(dff_dict)

app = dash.Dash(__name__)
fig = px.pie(dff, values = 'número de fundos', names = 'tipo', title = 'Teste' )

app.layout = dbc.Container(

    dbc.Row([
        dbc.Col([
#First Div, where objective of dashboard be presented
#This piece also include our logo on left side
#Few personalization options, simple template
            html.Div([
                html.Img(id='logo_png', src=app.get_asset_url("logo.png"), height= 50),               
                html.H5("Os fundos que acompanhamos estão dividos nas seguintes abaixo"),
#Phrase below our pie chart

            html.P('Selecione a classe que deseja obter mais informações'),
#Pie chart id created inside this .Div
            
            html.Div([                 
                    dcc.Graph(id = 'pie_class_chart', figure = fig,
                    style={'width': '100%', 'display': 'inline-block', 'vertical-align': 'right', })
                    ]),
        dbc.Col(
            html.Div([
                dash_table.DataTable(
                    id = 'tabela-dash',
                    columns = [{"id": i, "name": i} for i in dff.columns],
                    style_table={'height': '515px', 'overflowY': 'auto', 'display': 'inline-block', 'vertical-align':'left', 'float': 'left'},
                    style_data={
                    'color': 'black',
                  'backgroundColor': 'white'},
                  page_size= 15
                )
            ]),
        ),

            ]),
#Options of windowns, with click buttons                      
        ]),        
     ]),
)

  
#callback of datatable values
@app.callback(
    Output(component_id="tabela-dash", component_property='data'),
    Input(component_id = 'pie_class_chart', component_property='clickData'))

def display_click_data(clickData):
    if clickData != None:
        value = clickData['points'][0]['label']
        return dff[dff['tipo'] == value].to_dict('records')
    return dash.no_update


app.run_server(debug=True, use_reloader=False)

Output enter image description here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement