DataYoda
DataYoda

Reputation: 825

Send variable to Dash with call back in Python

is it possible to have a single app.callback running on different matrix inputs? update_figure_matrix is a function that return a figure based on input dataframe, I would like to call this function multi[ule time with different dataframe (matrix), but I don't know how.

@app.callback(Output('tabel-matrix', 'figure'), 
              [Input('checklist', 'value')] )
def update_figure_matrix(selected_value):

    matrix_filter = matrix[matrix['First'].isin(selected_value)]
    matrix_filter = matrix_filter[matrix_filter['Second'].isin(selected_value)]
    
    figure = px.scatter(
        matrix_filter, #dataframe
        x="First", #x
        y="Second", #y
        size="Total", #bubble size
        color="Total",#bubble color
        color_continuous_scale=px.colors.sequential.Plotly3, #color theme
        title="Data associated with first and second touchpoint", #chart title
    )
    figure.update_layout(
        xaxis_tickangle=30,#angle of the tick on x-axis
        title=dict(x=0.5), #set the title in center
        xaxis_tickfont=dict(size=9), #set the font for x-axis
        yaxis_tickfont=dict(size=9), #set the font for y-axis
        margin=dict(l=500, r=20, t=50, b=20), #set the margin
        paper_bgcolor="LightSteelblue", #set the background color for chart
    )    
    
    return figure



# I would like to call this code once with matrix1 (dataframe) and once with matrix2 (different dataframe) 
....
...
..


        dcc.Graph(id='tabel-matrix', #matrix = matrix1
               ),
        dcc.Graph(id='tabel-matrix', #matrix = matrix2
            
               ),

Upvotes: 0

Views: 218

Answers (1)

harisbal
harisbal

Reputation: 76

There are two possible approaches:

  1. include an additional input to your callback in order to specify which df you want to use:
matrices = {1: matrix1, 2: matrix2}

@app.callback(Output('table-matrix', 'figure'), 
              [Input('radioitems', 'value'), Input('checklist', 'value')])
def update_figure_matrix(matrix_no, selected_value):
    matrix = matrices[matrix_no]
    matrix_filter = matrix[matrix['First'].isin(selected_value)]
    matrix_filter = matrix_filter[matrix_filter['Second'].isin(selected_value)]
  1. for a more generic solution you may want to consider pattern-matching callbacks.

Upvotes: 1

Related Questions