Im trying to update a plotly express choropleth map in a callback. The initial map displays correctly but the when the dropdown triggers the callback an empty chart is displayed.
Importing the geojson with geopandas, and creating a new df
comm_dist_gj = gpd.read_file('./comm_dist_4326.geojson')
new_comm_dist = pd.DataFrame(comm_dist_gj.drop(columns='geometry'))
The function is here
def create_map(dataf, geoj):
fig = px.choropleth_mapbox(dataf,
geojson=geoj,
locations="district",
featureidkey="properties.district",
)
fig.update_layout(
mapbox_style="carto-positron",
mapbox_zoom=8,
mapbox_center = {"lat": 41.8, "lon": -87.8},
margin={"r":15,"t":15,"l":15,"b":15},
showlegend=False
)
fig.update_geos(fitbounds="locations", visible=False)
return fig
And the callback is here
@app.callback(
Output('commdist_map', 'figure'),
[Input('comm_dist_dropdown', 'value')])
def update_commdist_map(comm_dist_dropdown):
if comm_dist_dropdown == 0:
return create_map(new_comm_dist, comm_dist_gj)
else:
selected_commdist_gj = comm_dist_gj.loc[comm_dist_gj['district'] == str(comm_dist_dropdown)]
selected_commdist_df = new_comm_dist.loc[new_comm_dist['district'] == str(comm_dist_dropdown)]
return create_map(selected_commdist_df, selected_commdist_gj)
Ive tested the callback by returning a separate geojson file and df, it works fine. So Im thinking that it must be the way Im filtering for the selected district. Which I dont understand because after checking the data types for selected_commdist_gj
and selected_commdist_df
they’re the same as the original data types and do contain the proper rows.
Is there something wrong with the way Im filtering the geodataframe and dataframe?
UPDATE:
So I removed the creation of selected_commdist_gj
and selected_commdist_df
from the callback and placed it above outside of the callback. and used a random district to number to see if it would up date the map correctly. And it does, so there must be something I am doing wrong within the call back.
Here is how I updated the code
I put this in the code above the callback
selected_commdist_gj = comm_dist_gj.loc[comm_dist_gj['district'].isin(['1'])]
selected_commdist_df = new_comm_dist.loc[new_comm_dist['district'] == '1']
and updated my call back to just call the function with the new variables
@app.callback(
Output('commdist_map', 'figure'),
[Input('comm_dist_dropdown', 'value')])
def update_commdist_map(comm_dist_dropdown):
if comm_dist_dropdown == 0:
return create_map(new_comm_dist, comm_dist_gj)
else:
return create_map(selected_commdist_df, selected_commdist_gj)