✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🧬 Learn how to build RNA-Seq data apps with Python & Dash. Register for the May 20 Webinar!

Multiple callbacks sharing a variable

I am selecting the name of a portfolio from a Dropdown Menu. Using a callback I can update e.g. a graph. This update function would access a database which is kind of expensive. How can I load the portfolio only once and update multiple table and graphs?

Also, how do I get rid of those command buttons on top of all my graphs?

See https://github.com/plotly/dash/issues/49#issuecomment-311511286 for now. Copied from that link:

global_df = pd.read_csv('...')
app.layout = html.Div([
    dcc.Graph(id='graph'), 
    html.Table(id='table'),
    dcc.Dropdown(id='dropdown'),
    html.Div(id='intermediate-value', style={'display': 'none'})
])

@app.callback(Output('intermediate-value', 'children'), [Input('dropdown', 'value')])
def clean_data(value):
     # some expensive clean data step
     cleaned_df = your_expensive_clean_or_compute_step(value)
     return cleaned_df.to_json() # or, more generally, json.dumps(cleaned_df)

@app.callback(Output('graph', 'figure'), [Input('intermediate-value', 'children'])
def update_graph(jsonified_cleaned_data):
    dff = pd.read_json(jsonified_cleaned_data) # or, more generally json.loads(jsonified_cleaned_data)
    figure = create_figure(dff) 
    return figure

@app.callback(Output('table', 'children'), [Input('intermediate-value', 'children'])
def update_table(jsonified_cleaned_data):
    dff = pd.read_json(jsonified_cleaned_data) # or, more generally json.loads(jsonified_cleaned_data)
    table = create_table(dff) 
    return table

Also, how do I get rid of those command buttons on top of all my graphs?

See Is it possible to hide the floating toolbar?

For anyone in the future reading this, please check out a new section in the user guide on this topic: https://plot.ly/dash/sharing-data-between-callbacks

Hi, I followed the steps above, i.e. I only did the expensive query once, saved the jsonified result to a hidden html Div, and then created the graphs using that result.

However, my graphs now seem to be completely off and all over the place… they don’t make any sense. Before I jsonified the dataframe (and was repeatedly using the expensive query), they were fine. Any suggestions as to why this is happening/how to fix it would be great. Thanks in advance!

For context, this is what my graphs look like now.

06