02 hotspots
Uncomment and install leafmap if needed
In [ ]:
Copied!
# %pip install -q leafmap
# %pip install -q leafmap
Import dependencies
In [ ]:
Copied!
import pandas as pd
import geopandas as gpd
import leafmap as lm
import ipywidgets as widgets
from IPython.display import display
import pandas as pd
import geopandas as gpd
import leafmap as lm
import ipywidgets as widgets
from IPython.display import display
Set the STL neighborhood boundary and the baseline crime datafile to variables
In [ ]:
Copied!
nbhd = "https://raw.githubusercontent.com/lweber89/geocrime-stl/main/src/geocrime_stl/data/stl_neighborhoods.geojson"
crime_df = "https://raw.githubusercontent.com/lweber89/geocrime-stl/refs/heads/main/data/processed/slmpd_crime_data.parquet"
nbhd = "https://raw.githubusercontent.com/lweber89/geocrime-stl/main/src/geocrime_stl/data/stl_neighborhoods.geojson"
crime_df = "https://raw.githubusercontent.com/lweber89/geocrime-stl/refs/heads/main/data/processed/slmpd_crime_data.parquet"
Read the parquet into a pandas dataframe
In [ ]:
Copied!
df = pd.read_parquet(crime_df)
df = pd.read_parquet(crime_df)
Create lists that will populate pull-down menus (Year/Month and Offense Type)
- Note: "Other" is excluded from the list. 90Z (NIBRS) coded incidents are categorized as "other" by the SLMPD. The visualization of "other" may not be value-add. The color gradient is available for "other" and the code below can be quickly refactored to include "other" as an available to choice to produce hotspot maps.
In [ ]:
Copied!
df['date_time'] = pd.to_datetime(df['date_time'])
df['year_month'] = df['date_time'].dt.to_period('M').astype(str)
valid_periods = sorted(df['year_month'].unique())
categories = sorted(df[df['off_type'] != 'Other']['off_type'].unique()) #This line can be refactored to include "other"
df['date_time'] = pd.to_datetime(df['date_time'])
df['year_month'] = df['date_time'].dt.to_period('M').astype(str)
valid_periods = sorted(df['year_month'].unique())
categories = sorted(df[df['off_type'] != 'Other']['off_type'].unique()) #This line can be refactored to include "other"
Create and populate pull-down widgets with lists built above
In [ ]:
Copied!
period_dropdown = widgets.Dropdown(
options=valid_periods,
value=valid_periods[-1],
description='Time Period:',
)
type_dropdown = widgets.Dropdown(
options=categories,
value=categories[0],
description='Offense Type:',
)
period_dropdown = widgets.Dropdown(
options=valid_periods,
value=valid_periods[-1],
description='Time Period:',
)
type_dropdown = widgets.Dropdown(
options=categories,
value=categories[0],
description='Offense Type:',
)
Define color gradients for offense types
In [ ]:
Copied!
gradients = {
"Person": {
0.1: "#000044", 0.4: "#0022ff",
0.7: "#00d2ff", 1.0: "#ffffff"
},
"Property": {
0.1: "#220022", 0.4: "#4a00e0",
0.7: "#ff007f", 1.0: "#ffebee"
},
"Society": {
0.1: "#001a11", 0.4: "#004d40",
0.7: "#00ff66", 1.0: "#ffffff"
},
"Other": {
0.1: "#261a00", 0.4: "#ff9100",
0.7: "#ffea00", 1.0: "#ffffff"
}
}
gradients = {
"Person": {
0.1: "#000044", 0.4: "#0022ff",
0.7: "#00d2ff", 1.0: "#ffffff"
},
"Property": {
0.1: "#220022", 0.4: "#4a00e0",
0.7: "#ff007f", 1.0: "#ffebee"
},
"Society": {
0.1: "#001a11", 0.4: "#004d40",
0.7: "#00ff66", 1.0: "#ffffff"
},
"Other": {
0.1: "#261a00", 0.4: "#ff9100",
0.7: "#ffea00", 1.0: "#ffffff"
}
}
Initialize basemap and add neighborhood boundary lines
In [ ]:
Copied!
m = lm.Map( center = [38.649053322140226, -90.25028228759767],
zoom=11.5,
height="850px",
basemap = "CartoDB.DarkMatter",
zoom_control=False,
draw_control=False,
scale_control=False,
fullscreen_control=False,
toolbar_control=False,
)
gdf = gpd.read_file(nbhd)
gdf.crs = "EPSG:4326"
nbhd_line_style = {
"stroke": True,
"color": "#718096",
"weight": 1.0,
"opacity": 0.8,
"fillOpacity": 0.0,
}
m.add_gdf(
gdf,
layer_name="Neighborhood Bndy",
style=nbhd_line_style,
hover_style = nbhd_line_style,
highlight_style={},
info_mode = None
)
m = lm.Map( center = [38.649053322140226, -90.25028228759767],
zoom=11.5,
height="850px",
basemap = "CartoDB.DarkMatter",
zoom_control=False,
draw_control=False,
scale_control=False,
fullscreen_control=False,
toolbar_control=False,
)
gdf = gpd.read_file(nbhd)
gdf.crs = "EPSG:4326"
nbhd_line_style = {
"stroke": True,
"color": "#718096",
"weight": 1.0,
"opacity": 0.8,
"fillOpacity": 0.0,
}
m.add_gdf(
gdf,
layer_name="Neighborhood Bndy",
style=nbhd_line_style,
hover_style = nbhd_line_style,
highlight_style={},
info_mode = None
)
Create infrastructure to create heatmap based on user choice (via pulldown menus)
In [ ]:
Copied!
def update_heatmap(change=None):
chosen_period = period_dropdown.value
chosen_type = type_dropdown.value
layer_name = f"Hotspots: {chosen_type} ({chosen_period})"
for layer in list(m.layers):
if layer.name.startswith("Hotspots:"):
m.remove_layer(layer)
filtered_df = df[(df['year_month'] == chosen_period) & (df['off_type'] == chosen_type)]
filtered_df['weight'] = 1 #This column is added to meet requirement of add_heatmap (value parameter)
if filtered_df.empty:
return
# Add the fresh, single heatmap layer
m.add_heatmap(
data=filtered_df,
latitude ="lat", # Adjust to match your exact parquet column name
longitude ="lon", # Adjust to match your exact parquet column name
value = "weight",
radius=35,
blur=15,
gradient=gradients[chosen_type],
name=layer_name
)
period_dropdown.observe(update_heatmap, names='value')
type_dropdown.observe(update_heatmap, names='value')
update_heatmap()
controls = widgets.HBox([period_dropdown, type_dropdown])
display(controls)
display(m)
def update_heatmap(change=None):
chosen_period = period_dropdown.value
chosen_type = type_dropdown.value
layer_name = f"Hotspots: {chosen_type} ({chosen_period})"
for layer in list(m.layers):
if layer.name.startswith("Hotspots:"):
m.remove_layer(layer)
filtered_df = df[(df['year_month'] == chosen_period) & (df['off_type'] == chosen_type)]
filtered_df['weight'] = 1 #This column is added to meet requirement of add_heatmap (value parameter)
if filtered_df.empty:
return
# Add the fresh, single heatmap layer
m.add_heatmap(
data=filtered_df,
latitude ="lat", # Adjust to match your exact parquet column name
longitude ="lon", # Adjust to match your exact parquet column name
value = "weight",
radius=35,
blur=15,
gradient=gradients[chosen_type],
name=layer_name
)
period_dropdown.observe(update_heatmap, names='value')
type_dropdown.observe(update_heatmap, names='value')
update_heatmap()
controls = widgets.HBox([period_dropdown, type_dropdown])
display(controls)
display(m)