Python Dash app doesn't display scatter_mapbox properly in callback

I’m trying to create an interactive Dash app to show a map of prices that change when a drop-down is updated. I have successfully created this plot in a Jupyter notebook and inside a Dash app without a callback. The issue seems to be happening with the callback portion.

This is what I expect to see:
enter image description here

But this is what I see:

Here is a portion of the code that I am using for the Dash app:


################### Create App ##########

app = dash.Dash(__name__)
server = app.server


############# CREATE CODE DROPDOWN #######
codes = df1.code.unique() # unique codes for dropdown menu
codes.sort()



############### APP LAYOUT ###############

app.layout = html.Div([
    
                        html.Div([ # labels for dropdowns
                                    html.Label("Service Code", style = {'margin-left':22, 
                                                                        'display': 'inline-block',
                                                                        'width': '200px',
                                                                        'font-weight': 'bold',
                                                                        'font-size': 12,
                                                                        'font-family': 'Arial'})
                        ]),
                        
                        html.Div([ # code dropdown
                                
                                dcc.Dropdown(id='group-select', 
                                             options=[{'label': i, 'value': i} for i in codes],
                                             value=43239, style={'width': '200px',
                                                                 'margin-left': 10, 
                                                                 'margin-right':10, 
                                                                 'margin-bottom':5, 
                                                                 'display': 'inline-block',
                                                                 'font-family': 'Arial'
                                                                 })
                                 ]),
                           
    
                            html.Div( # chart
                                      [dcc.Graph('graph2'                                              
                                                  )
                                      ],
                                      
                                     )
                           
                      ])

@app.callback(
    Output(component_id = 'graph2', component_property = 'figure'),
    Input(component_id = 'group-select', component_property = 'value')
    )
def update_graph2(grpname):
    
    df1 = df1[(df1.code == grpname)]
    


    fig2 = px.scatter_mapbox(df1,
                     lat='lat', lon='long', color ='price',
                           size_max=15, zoom=10,
                           width = 500)

    fig2.update_layout(
        mapbox_style="carto-positron")

    fig2.update_traces(marker={'size': 15})

    fig2.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
    
    return (fig2)


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

Is there something obvious that I am missing that is making the call back not work properly? Again, if I don’t use a callback and just return the map, everything appears as it should.

@adamschroeder I have been watching your tutorials so maybe you would be able to help me here. I appreciate the time.

Hey @ryangifford , welcome to community.

I created some fake data and run your code.

import pandas as pd
#------------------------------------
import dash
import dash_table
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output, State
#------------------------------------
import plotly.graph_objects as go
import plotly.express as px


app = dash.Dash(__name__)
server = app.server

#FAKE DATA
df1 = pd.DataFrame()
df1['code'] = ['Ankit', 'Ankita', 'Yashvardhan']
df1['lat'] = ['38', '39', '40']
df1['long'] = ['24', '25', '26']
df1['price'] = ['2224', '2225', '2226']
############# CREATE CODE DROPDOWN #######
codes = df1.code.unique() # unique codes for dropdown menu
codes.sort()



############### APP LAYOUT ###############

app.layout = html.Div([
    
                        html.Div([ # labels for dropdowns
                                    html.Label("Service Code", style = {'margin-left':22, 
                                                                        'display': 'inline-block',
                                                                        'width': '200px',
                                                                        'font-weight': 'bold',
                                                                        'font-size': 12,
                                                                        'font-family': 'Arial'})
                        ]),
                        
                        html.Div([ # code dropdown
                                
                                dcc.Dropdown(id='group-select', 
                                             options=[{'label': i, 'value': i} for i in codes],
                                             value=43239, style={'width': '200px',
                                                                 'margin-left': 10, 
                                                                 'margin-right':10, 
                                                                 'margin-bottom':5, 
                                                                 'display': 'inline-block',
                                                                 'font-family': 'Arial'
                                                                 })
                                 ]),
                           
    
                            html.Div( # chart
                                      [dcc.Graph('graph2'                                              
                                                  )
                                      ],
                                      
                                     )
                           
                      ])

@app.callback(
    Output('graph2', 'figure'),
    Input('group-select', 'value')
    )
def update_graph2(grpname):
    
    df2 = df1[(df1.code == grpname)]       #if i use df1 here instead df2 it gives me error -> "UnboundLocalError: local variable 'df1' referenced before assignment"
    


    fig2 = px.scatter_mapbox(df2,
                     lat='lat', lon='long', color ='price',
                           size_max=15, zoom=10,
                           width = 500)

    fig2.update_layout(
        mapbox_style="carto-positron")

    fig2.update_traces(marker={'size': 15})

    fig2.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
    
    return fig2


Have a nice day.

1 Like

@akroma This worked perfectly. Thanks for the help. Just out of curiosity, where did you find the error “UnboundLocalError: local variable ‘df1’ referenced before assignment”?