Cannot update figure using button

I was trying to update a plot using a button as a trigger, but for some reason, the figure is not displayed. I reproduced the problem using the following example:

import dash
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_core_components as dcc

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

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


app.layout = html.Div(
    [
        html.Div(dcc.Input(id="title", type="text")),
        html.Button("Submit", id="button", n_clicks=0),
        html.Div(dcc.Graph(id="bar_graph")),
    ]
)


@app.callback(
    dash.dependencies.Output("bar_graph", "figure"),
    [Input("button", "n_clicks")],
    [State("title", "value")],
)
def update_output(n_clicks, title):
    if n_clicks > 0:
        return {
            "data": [
                {"x": [1, 2, 3], "y": [4, 1, 2], "type": "bar", "name": "SF"},
                {"x": [1, 2, 3], "y": [2, 4, 5], "type": "bar", "name": u"Montréal"},
            ],
            "layout": {"title": title},
        }


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

and this is what I got:

I am using:
python = 3.7.0
plotly = 4.0.0
dash = 1.0.2
dash_core_components = 1.0.0
dash_html_components = 1.0.0

Thanks for your help!
Mike

Use another platform…Like spyder or Pycharm… I executed the same program given above… And when i press the submit button,the figure is displayed!

1 Like

Hey your code is good but the function returns nothing if n_clicks is 0. This implicitly returns None to the figure property of the graph which throws the error.

All you need is:

def update_output(n_clicks, title):
    if n_clicks > 0:
        return {
            "data": [
                {"x": [1, 2, 3], "y": [4, 1, 2], "type": "bar", "name": "SF"},
                {"x": [1, 2, 3], "y": [2, 4, 5], "type": "bar", "name": u"Montréal"},
            ],
            "layout": {"title": title},
        }
    return {}

and it works.

You can reproduce the error by explicitly returning None:

def update_output(n_clicks, title):
    if n_clicks > 0:
        return {
            "data": [
                {"x": [1, 2, 3], "y": [4, 1, 2], "type": "bar", "name": "SF"},
                {"x": [1, 2, 3], "y": [2, 4, 5], "type": "bar", "name": u"Montréal"},
            ],
            "layout": {"title": title},
        }
    return None
1 Like

@russellthehippo You solution works! Thank you very very much, and really appreciate your explanation! Lesson learn here, as I thought I can be lazy for skipping one of the return.

three reasons why you should buy plotly pro: support open source, get great support, host your plots and dashboards online