2

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?

helvete
  • 2,455
  • 13
  • 33
  • 37
Agustin
  • 1,458
  • 1
  • 13
  • 30

2 Answers2

5

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

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
girl7
  • 61
  • 2
  • 4
2

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)
Niko Föhr
  • 28,336
  • 10
  • 93
  • 96
  • Thank you, this works to clear the figure however it changes the format. Is there a way to revert it back to the original format created by just html.Div( dcc.Graph(id = 'graph') ) ? – Agustin Jul 17 '20 at 13:49
  • 1
    The callback will change everything inside the `figure` property. If you want to keep everything similar, use same function to create the figure initially to `dcc.Graph` and to create the empty figure in the callback. You can use whatever type of figure you want: scatterplot, barplot, ... etc. – Niko Föhr Jul 17 '20 at 13:59