Will
Will

Reputation: 421

How to return a Plotly choropleth from a callback

I'm trying to return a choropleth map in plotly from a callback using dash core components.

Here is the graph reference from the layout:

from dash import dcc
df = pd.read_csv("states.csv")
app.layout = html.Div([

...

    dcc.Graph(id='my_bee_map', figure={})
])

@app.callback(
    [Output(component_id='my_bee_map', component_property='figure')],
    [Input(component_id='slct_year', component_property='value')]
)
def update_graph(option_slctd):
    container = "The year chosen by user was: {}".format(option_slctd)

    dff = df.copy()
    print(dff)

    # Plotly Express
    fig = px.choropleth(
        data_frame=dff,
        locationmode='USA-states',
        locations='state_code',
        scope="usa",
        color='Count',
        hover_data=['Count'],
        color_continuous_scale=px.colors.sequential.YlOrRd,
        labels={'Count': 'Count'},
        template='plotly_dark'
    )

    return fig

The states.csv file consists of two columns, 'state_code' and 'Count'. Running the code produces the following error:

dash._grouping.SchemaTypeValidationError: Schema: [<Output `my_bee_map.figure`>]
                Path: ()
                Expected type: (<class 'tuple'>, <class 'list'>)
                Received value of type <class 'plotly.graph_objs._figure.Figure'>:
                    Figure({
    'data': [{'coloraxis': 'coloraxis',
              'customdata': array([[4302],
                                   [8008],
...
                                   [   1],
                                   [   1],
                                   [   1]], 
                             dtype=int64),
...
})

I want to just return the choropleth object to display it in the layout. Thanks!

Upvotes: 1

Views: 94

Answers (1)

Hamzah Al-Qadasi
Hamzah Al-Qadasi

Reputation: 9786

The problem is in the way of writing the @app.callback, try to correct it as:

@app.callback(
    Output(component_id="graph", component_property="figure"), 
    Input(component_id="candidate",component_property= "value")) 

instead of :

@app.callback(
    [Output(component_id="graph", component_property="figure")], 
    [Input(component_id="candidate",component_property= "value")])

Use square brackets only if you have multiple inputs or outputs.

Upvotes: 1

Related Questions