Search code examples
pythongeojsonplotly-dashchoropleth

Plotly Dash Callback error updating Output Graph with Choropleth


Iam trying to update a choropleth but this only works when I define the figure outside of the callback like this:

fig = px.choropleth(
    df,
    geojson=counties,
    locations='COV_',
    color='Enero')

fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})


APP.layout = html.Div([
    dbc.FormGroup(
            [
                dbc.Label("Tipo de delito"),
                dcc.Dropdown(
                    id="in-delito",
                    value=NE['Tipo de delito'].unique()[0],
                    options=[
                        {"label": col, "value": col} for col in NE['Tipo de delito'].unique()
                    ]
                ),
            ]
    ),

    dcc.Graph(id="gr-delito-map", figure=fig)

])

But when try to update with a callback like this:

@APP.callback(
    [dash.dependencies.Output('gr-delito-map', 'figure')],
    [dash.dependencies.Input('in-delito', 'value')]
)
def update_delito(value):

    global counties

    df = pd.read_csv(BASE_PATH+'/../Descargador/data/ne.csv')
    df = df.filter(["Año", "Clave_Ent", "Tipo de delito", "Enero"])
    #df = df[df['Tipo de delito']=='Homicidio']
    df = df[df['Tipo de delito']==value]
    df[["Enero"]] = df[["Enero"]].apply(pd.to_numeric)
    df = df.groupby('Clave_Ent').sum()
    df=df.reset_index()
    df['COV_'] = df['Clave_Ent'].astype(str)

    fig = px.choropleth(
            df,
            geojson=counties,
            locations='COV_',
            color='Enero')

    return fig

Never works and I only get a 'callback error updating' error.

I try a similar piece of code to this that work in this link:

https://community.plot.ly/t/how-to-update-a-choropleth-map/23340/2

But for any reason this doesn't work with this figure or data.

And the error in the display doesn't show information.

Any idea about how can I fix this?

Thanks


Solution

  • Only is necessary to return a list with the fig inside return [fig]