Hello all,
I am having troubles getting my choropleth map to display data.
I use the crime.csv
table from https://www.kaggle.com/ankkur13/boston-crime-data, and I am using a GEOJSON file from Boston Analytics (Fetched in the script). Currently, my code runs without errors, but it does not load the data onto the plot.
import pandas as pd
import plotly.graph_objs as go
from urllib.request import urlopen
import json
# Read Dataset
# Located at: https://www.kaggle.com/ankkur13/boston-crime-data
df = pd.read_csv("crime.csv")
with urlopen('http://bostonopendata-boston.opendata.arcgis.com/datasets/9a3a8c427add450eaf45a470245680fc_5.geojson?outSR={%22latestWkid%22:2249,%22wkid%22:102686}') as response:
pd_districts = json.load(response)
df_agg = df.groupby("DISTRICT").agg(CRIMES=("YEAR","count"))
df_agg.reset_index(inplace=True)
df_agg = df_agg[df_agg['DISTRICT'] != 'nan']
df['DISTRICT'] = df['DISTRICT'].apply(lambda x: str(x))
fig = go.Figure(go.Choroplethmapbox(geojson=pd_districts,
locations=df_agg['DISTRICT'],
z=df_agg['CRIMES']))
fig.update_layout(mapbox_style="carto-positron")
fig.update_geos(fitbounds="locations")
fig.show()
I believe it has something to do with my featureidkey
. However, I have tried multiple variants such as properties.DISTRICT
, properties.ID
, but to no avail.
I also ran a few sanity checks to make sure that the data was accessible, and here they are:
print(df_agg['DISTRICT'].unique())
print(pd_districts['features'][0]['properties']['ID'])
print(df['DISTRICT'].dtype)
I can load this data into a folium choropleth map if I remove every other entry:
import pandas as pd
import folium
m = folium.Map(location=[42.3, -71.05], zoom_start=11, tiles='cartodbpositron')
folium.Choropleth(geo_data='police_districts_tst.geojson',
data=df_agg,
columns=['DISTRICT', 'CRIMES'],
key_on='properties.DISTRICT',
fill_color='YlGn',
fill_opacity=0.6,
line_opacity=0.2,
).add_to(m)
m
Any help would be appreciated, as I would eventually like to build a dash application, and I would be unable to do that with a Folium Choropleth.