I have been able to successfully create a custom shapefile Choropleth map using plotly and geopandas. It loads successfully in my Jupyter window. The following image is what the map looks like when running in Jupyter.
Successfully rendered map in Jupyter
This is the code used to render the above map:
data = go.Choroplethmapbox(
geojson = gdf_json,
locations = df.index.astype(str),
z = df['2016']['Total'],
text = df.index.astype(str),
colorbar=dict(thickness=20,ticklen=3,tickformat=',.2r',outlinewidth=0),
marker_line_width=0.5,
marker_opacity=0.4,
colorscale='gnbu',
zmin=zmin,
zmax=zmax,
hovertemplate = "<b>%{text}</b><br>" +
"%{z:,.4r}<br>" +
"<extra></extra>")
#mapbox geographic map layout
layout = go.Layout(
title='Expenditure, 2020',
autosize=True,
#hovermode='closest',
#showlegend=True,
height=600,
margin=dict(l=0, r=0, t=40, b=0),
mapbox = dict(
domain = {'x': [0, 1],'y': [0, 1]},
center = dict(lat=-27.628296146695863, lon=152.74025612708698),
accesstoken = MAPBOX_ACCESSTOKEN,
#pitch=0,
zoom=10,
style='light')
)
fig = go.Figure(data=data, layout=layout)
fig.show()
However, when I attempt to load the map into Dash, it returns as an empty graph. (Note I cancel out the fig.show() line of code during this process).
app.layout = html.Div([
dcc.Graph(id = 'plot', figure = fig)
])
if __name__ == '__main__':
app.run_server()
What I have tried
To narrow down the potential problems, I have tried to load in other elements such as dropdowns, radio buttons and a range slider. These loaded successfully, just not the map itself. I am also using the correct public Mapbox API token, as I have previously loaded up a Scattermapbox graph (created a bubble map), which has been successful on Dash.
Possible reasons
Obviously the starting point is whether there might be a very small minor syntax error in my code.
However I'm also wondering if there's something wrong with the loading of the geojson? Even though it loads successfully in Jupyter, maybe there is a slightly different method used when loading it into Dash?
To convert my geopandas polygons into geojson:
- I converted it into an appropriate CRS -->
gdf.to_crs(epsg=4326) - Set the index to my unique id -->
gdf.set_index(id) - Applied this function --> gdf_json =
gdf.__geo_interface__
Would love some help if possible. Thank you!