Agustin
Agustin

Reputation: 1526

How to clear dash figure with callback

I've got a graph that I want to reset to the original state, seen in picture: the original state

I tried this, as if I print the initial state of figure it says None.

app.layout = html.Div([
    html.Div(
        dcc.Graph(id = 'graph')
    )
])
           
@app.callback(
    Output('graph', 'figure'),
    [Input('click', 'clickedData')])
def myfun(x): 
    ...
    return None

But I get the error: Cannot read property 'layout' of null

What should I return so my new graph returns to original empty state?

Upvotes: 2

Views: 9278

Answers (2)

girl7
girl7

Reputation: 71

It should help to return empty figure: fig = {}.
In the callback just write return {} instead of return None.

Upvotes: 5

Niko Fohr
Niko Fohr

Reputation: 33740

You should return a go.Figure object since it will be placed into the figure property of the dcc.Graph. You can make empty figure by giving x=[], y=[] to the arguments of the go.Figure:

@app.callback(Output('graph', 'figure'), [Input('click', 'n_clicks')])
def myfun(n_clicks):
    if not n_clicks:
        raise dash.exceptions.PreventUpdate
    fig = go.Figure(data=[go.Scatter(x=[], y=[])])
    return fig

(Full app code below)

Before and after click

Full app code

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from dash.dependencies import Input, Output

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 1, 2])])

app.layout = html.Div(children=[
    html.H1(children='Test app'),
    dcc.Graph(id='graph', figure=fig),
    html.Button('Click to empty', id='click')
])


@app.callback(Output('graph', 'figure'), [Input('click', 'n_clicks')])
def myfun(n_clicks):
    if not n_clicks:
        raise dash.exceptions.PreventUpdate
    fig = go.Figure(data=[go.Scatter(x=[], y=[])])
    return fig


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

Upvotes: 4

Related Questions