Spaces:
Build error
Build error
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +310 -279
src/streamlit_app.py
CHANGED
|
@@ -17,37 +17,11 @@ from pathlib import Path
|
|
| 17 |
os.environ["STREAMLIT_CONFIG_DIR"] = "/tmp/.streamlit"
|
| 18 |
Path(os.environ["STREAMLIT_CONFIG_DIR"]).mkdir(parents=True, exist_ok=True)
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
st.
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
)
|
| 26 |
-
st.markdown("""
|
| 27 |
-
<style>
|
| 28 |
-
.title {
|
| 29 |
-
text-align: center;
|
| 30 |
-
padding: 25px;
|
| 31 |
-
}
|
| 32 |
-
</style>
|
| 33 |
-
""", unsafe_allow_html=True)
|
| 34 |
-
|
| 35 |
-
st.markdown("<div class='title'><h1> LAPD Crime Insights Dashboard </h1></div>", unsafe_allow_html=True)
|
| 36 |
-
|
| 37 |
-
# 1. Page title
|
| 38 |
-
st.markdown(""" This application provides a suite of interactive visualizations—pie charts, bar charts, scatter plots, and more—that let you explore crime patterns in the LAPD dataset from multiple angles. Quickly see which offense categories dominate, compare arrest rates against non-arrests, track how crime volumes change over time, and examine geographic hotspots. These insights can help police departments, community organizations, and policymakers allocate resources more effectively and design targeted strategies to improve public safety.""")
|
| 39 |
-
|
| 40 |
-
# 2. Data info & load
|
| 41 |
-
st.header("Dataset Information")
|
| 42 |
-
st.markdown(
|
| 43 |
-
"""
|
| 44 |
-
- **Source:** LAPD crime incidents dataset
|
| 45 |
-
- **Rows:** incidents (one per row)
|
| 46 |
-
- **Columns:** e.g. `crm_cd_desc` (crime type), `arrest` (boolean), `date`, `location_description`, etc.
|
| 47 |
-
- **Purpose:** Interactive exploration of top crime categories and arrest rates.
|
| 48 |
-
"""
|
| 49 |
-
)
|
| 50 |
-
|
| 51 |
|
| 52 |
# Define paths.
|
| 53 |
# Path for geo_json.
|
|
@@ -66,200 +40,255 @@ DATA_PATH = Path(__file__).parent / "crime_data.csv" # /app/src/crime_dat
|
|
| 66 |
@st.cache_data
|
| 67 |
def load_data():
|
| 68 |
return pd.read_csv(DATA_PATH)
|
| 69 |
-
|
| 70 |
-
if st.button("🔄"):
|
| 71 |
-
st.cache_data.clear() # Clear the cache
|
| 72 |
-
st.toast("Data is refreshed",icon="✅") # Reload the data
|
| 73 |
-
|
| 74 |
-
# 2. Load and early‐exit if missing
|
| 75 |
-
df = load_data()
|
| 76 |
-
if df.empty:
|
| 77 |
-
st.stop()
|
| 78 |
-
|
| 79 |
-
# 3. Data preview
|
| 80 |
-
st.header("Data Preview")
|
| 81 |
-
st.write(f"Total records: {df.shape[0]} | Total columns: {df.shape[1]}")
|
| 82 |
-
st.dataframe(df.head())
|
| 83 |
-
|
| 84 |
-
# Pie Chart 1: Top 10 Crime Types
|
| 85 |
-
st.markdown("<div class='title'><h1> Top 10 Crime Type </h1></div>", unsafe_allow_html=True)
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
)
|
| 100 |
|
| 101 |
-
#
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
else:
|
| 105 |
-
filtered = df[df["year"] == selected_year]
|
| 106 |
-
|
| 107 |
-
# Compute top 10 crime types for that year ──
|
| 108 |
-
top_crimes = (
|
| 109 |
-
filtered["crm_cd_desc"]
|
| 110 |
-
.value_counts()
|
| 111 |
-
.nlargest(10)
|
| 112 |
-
.rename_axis("Crime Type")
|
| 113 |
-
.reset_index(name="Count")
|
| 114 |
-
)
|
| 115 |
-
top_crimes["Percentage"] = top_crimes["Count"] / top_crimes["Count"].sum()
|
| 116 |
-
|
| 117 |
-
#Key Metrics
|
| 118 |
-
st.markdown("### Key Metrics", unsafe_allow_html=True)
|
| 119 |
-
col1, col2, col3 = st.columns(3)
|
| 120 |
-
col1.metric(
|
| 121 |
-
label="Total Incidents",
|
| 122 |
-
value=f"{len(filtered):,}"
|
| 123 |
-
)
|
| 124 |
-
col2.metric(
|
| 125 |
-
label="Unique Crime Types",
|
| 126 |
-
value=f"{filtered['crm_cd_desc'].nunique():,}"
|
| 127 |
-
)
|
| 128 |
-
# compute share of the top crime
|
| 129 |
-
top_share = top_crimes.iloc[0]["Percentage"]
|
| 130 |
-
col3.metric(
|
| 131 |
-
label=f"Share of Top Crime ({top_crimes.iloc[0]['Crime Type']})",
|
| 132 |
-
value=f"{top_share:.1%}"
|
| 133 |
-
)
|
| 134 |
-
|
| 135 |
|
| 136 |
-
#
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
color_discrete_sequence=px.colors.sequential.Agsunset,
|
| 143 |
-
title=" "
|
| 144 |
-
)
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
textinfo="label+percent",
|
| 149 |
-
pull=[0.05] * len(top_crimes),
|
| 150 |
-
marker=dict(line=dict(color="white", width=2))
|
| 151 |
-
)
|
| 152 |
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
-
# Display the plot.
|
| 161 |
-
st.plotly_chart(fig, use_container_width=True)
|
| 162 |
|
| 163 |
-
#
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
|
| 167 |
# -------------------------------- Plot 2: Heat Map --------------------------------
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
ax.
|
| 190 |
-
ax.
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
| 202 |
|
| 203 |
|
| 204 |
# -------------------------------- Plot 3: Line Chart --------------------------------
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
|
|
|
| 236 |
|
| 237 |
|
| 238 |
# -------------------------------- Plot 4: Map --------------------------------
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
-
#
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
#
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
#
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
#
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
# Add county boundary
|
| 262 |
-
folium.GeoJson(geojson_data, name="County Boundaries").add_to(new_map)
|
| 263 |
|
| 264 |
# # Create the map.
|
| 265 |
# def crime_map(year, crime):
|
|
@@ -282,79 +311,81 @@ folium.GeoJson(geojson_data, name="County Boundaries").add_to(new_map)
|
|
| 282 |
# # Call the function with selected values
|
| 283 |
# crime_map(year_dropdown, crime_dropdown)
|
| 284 |
|
| 285 |
-
# Using for-loop to add the crime points
|
| 286 |
-
for _, row in df_filtered.iterrows():
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
# Display the new map.
|
| 297 |
-
st_folium(new_map, width=1000, height=800)
|
| 298 |
-
|
| 299 |
-
# Description.
|
| 300 |
-
st.markdown("""
|
| 301 |
-
This visualization uses Folium to build an interactive map of crime distribution in Los Angeles, highlighting the geospatial clustering characteristics of different years and crime types, and emphasizing the user's experience of freely exploring the map. The base map uses real streets and geographic backgrounds to enhance the spatial visualization of the image. The map shows the administrative boundaries of Los Angeles County in blue polygons, which are loaded with GeoJSON data and overlaid on the map to specify the geographic boundaries of crime locations. The red dots on the map represent the location of individual crimes, and the system samples no more than 300 data items from this category for visualization, with each dot pinpointed by latitude and longitude coordinates. The map supports full Leaflet.js functionality, including zooming, dragging, layer control, and other operations, which greatly enhances the flexibility of data exploration. A drop-down menu in the upper left corner of the page allows users to customize filters for specific years and crime types, enabling instant updates to the map content.
|
| 302 |
-
""")
|
| 303 |
|
| 304 |
# -------------------------------- Plot 4: Stacked Bar Chart --------------------------------
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
)
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
|
|
|
| 329 |
|
| 330 |
# -------------------------------- Plot 5: Bar Chart --------------------------------
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
)
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
This
|
| 360 |
-
|
|
|
|
|
|
| 17 |
os.environ["STREAMLIT_CONFIG_DIR"] = "/tmp/.streamlit"
|
| 18 |
Path(os.environ["STREAMLIT_CONFIG_DIR"]).mkdir(parents=True, exist_ok=True)
|
| 19 |
|
| 20 |
+
# Set up sidebar menu for navigation.
|
| 21 |
+
st.sidebar.title("LA Crime Data Dashboard")
|
| 22 |
+
page = st.sidebar.radio(
|
| 23 |
+
"Select Visualization",
|
| 24 |
+
["Home", "Pie Chart", "Heat Map", "Line Chart", "Map", "Stacked Bar Chart", "Bar Chart"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
# Define paths.
|
| 27 |
# Path for geo_json.
|
|
|
|
| 40 |
@st.cache_data
|
| 41 |
def load_data():
|
| 42 |
return pd.read_csv(DATA_PATH)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
# ── 0. Page configuration ──
|
| 45 |
+
if page == "Home":
|
| 46 |
+
st.set_page_config(
|
| 47 |
+
page_title="Analyze Crime Distributions",
|
| 48 |
+
page_icon="📊",
|
| 49 |
+
layout="wide"
|
| 50 |
+
)
|
| 51 |
+
st.markdown("""
|
| 52 |
+
<style>
|
| 53 |
+
.title {
|
| 54 |
+
text-align: center;
|
| 55 |
+
padding: 25px;
|
| 56 |
+
}
|
| 57 |
+
</style>
|
| 58 |
+
""", unsafe_allow_html=True)
|
| 59 |
+
|
| 60 |
+
st.markdown("<div class='title'><h1> LAPD Crime Insights Dashboard </h1></div>", unsafe_allow_html=True)
|
| 61 |
+
|
| 62 |
+
# 1. Page title
|
| 63 |
+
st.markdown(""" This application provides a suite of interactive visualizations—pie charts, bar charts, scatter plots, and more—that let you explore crime patterns in the LAPD dataset from multiple angles. Quickly see which offense categories dominate, compare arrest rates against non-arrests, track how crime volumes change over time, and examine geographic hotspots. These insights can help police departments, community organizations, and policymakers allocate resources more effectively and design targeted strategies to improve public safety.""")
|
| 64 |
+
|
| 65 |
+
# 2. Data info & load
|
| 66 |
+
st.header("Dataset Information")
|
| 67 |
+
st.markdown(
|
| 68 |
+
"""
|
| 69 |
+
- **Source:** LAPD crime incidents dataset
|
| 70 |
+
- **Rows:** incidents (one per row)
|
| 71 |
+
- **Columns:** e.g. `crm_cd_desc` (crime type), `arrest` (boolean), `date`, `location_description`, etc.
|
| 72 |
+
- **Purpose:** Interactive exploration of top crime categories and arrest rates.
|
| 73 |
+
"""
|
| 74 |
)
|
| 75 |
|
| 76 |
+
# # Define paths.
|
| 77 |
+
# # Path for geo_json.
|
| 78 |
+
# GEOJSON_PATH = Path(__file__).parent / "County_Boundary.geojson"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
# # Handle the error for geo_json.
|
| 81 |
+
# try:
|
| 82 |
+
# gdf_counties = gpd.read_file(GEOJSON_PATH)
|
| 83 |
+
# except FileNotFoundError:
|
| 84 |
+
# st.error("Error: 'County_Boundary.geojson' file not found in the /app/src/ directory. Please ensure the file is included in the project.")
|
| 85 |
+
# st.stop()
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
# # Path for crime data.
|
| 88 |
+
# DATA_PATH = Path(__file__).parent / "crime_data.csv" # /app/src/crime_data.csv
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
# @st.cache_data
|
| 91 |
+
# def load_data():
|
| 92 |
+
# return pd.read_csv(DATA_PATH)
|
| 93 |
+
|
| 94 |
+
if st.button("🔄"):
|
| 95 |
+
st.cache_data.clear() # Clear the cache
|
| 96 |
+
st.toast("Data is refreshed",icon="✅") # Reload the data
|
| 97 |
+
|
| 98 |
+
# 2. Load and early‐exit if missing
|
| 99 |
+
df = load_data()
|
| 100 |
+
if df.empty:
|
| 101 |
+
st.stop()
|
| 102 |
+
|
| 103 |
+
# 3. Data preview
|
| 104 |
+
st.header("Data Preview")
|
| 105 |
+
st.write(f"Total records: {df.shape[0]} | Total columns: {df.shape[1]}")
|
| 106 |
+
st.dataframe(df.head())
|
| 107 |
+
|
| 108 |
+
elif page == "Pie Chart":
|
| 109 |
+
# Pie Chart 1: Top 10 Crime Types
|
| 110 |
+
st.markdown("<div class='title'><h1> Top 10 Crime Type </h1></div>", unsafe_allow_html=True)
|
| 111 |
+
|
| 112 |
+
years = sorted(df["year"].dropna().astype(int).unique())
|
| 113 |
+
# Prepend an “All” option
|
| 114 |
+
options = ["All"] + years
|
| 115 |
+
|
| 116 |
+
# Year filter (shorter, above chart)
|
| 117 |
+
col_empty, col_filter = st.columns([3,1])
|
| 118 |
+
with col_filter:
|
| 119 |
+
selected_year = st.selectbox(
|
| 120 |
+
"Select Year",
|
| 121 |
+
options=options,
|
| 122 |
+
index=0, # default to “All”
|
| 123 |
+
key="year_filter"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# Filter according to selection
|
| 127 |
+
if selected_year == "All":
|
| 128 |
+
filtered = df.copy()
|
| 129 |
+
else:
|
| 130 |
+
filtered = df[df["year"] == selected_year]
|
| 131 |
+
|
| 132 |
+
# Compute top 10 crime types for that year ──
|
| 133 |
+
top_crimes = (
|
| 134 |
+
filtered["crm_cd_desc"]
|
| 135 |
+
.value_counts()
|
| 136 |
+
.nlargest(10)
|
| 137 |
+
.rename_axis("Crime Type")
|
| 138 |
+
.reset_index(name="Count")
|
| 139 |
+
)
|
| 140 |
+
top_crimes["Percentage"] = top_crimes["Count"] / top_crimes["Count"].sum()
|
| 141 |
+
|
| 142 |
+
#Key Metrics
|
| 143 |
+
st.markdown("### Key Metrics", unsafe_allow_html=True)
|
| 144 |
+
col1, col2, col3 = st.columns(3)
|
| 145 |
+
col1.metric(
|
| 146 |
+
label="Total Incidents",
|
| 147 |
+
value=f"{len(filtered):,}"
|
| 148 |
+
)
|
| 149 |
+
col2.metric(
|
| 150 |
+
label="Unique Crime Types",
|
| 151 |
+
value=f"{filtered['crm_cd_desc'].nunique():,}"
|
| 152 |
+
)
|
| 153 |
+
# compute share of the top crime
|
| 154 |
+
top_share = top_crimes.iloc[0]["Percentage"]
|
| 155 |
+
col3.metric(
|
| 156 |
+
label=f"Share of Top Crime ({top_crimes.iloc[0]['Crime Type']})",
|
| 157 |
+
value=f"{top_share:.1%}"
|
| 158 |
+
)
|
| 159 |
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
# -------------------------------- Plot 1: Pie(Donut) Chart --------------------------------
|
| 162 |
+
elif page == "Pie Chart":
|
| 163 |
+
fig = px.pie(
|
| 164 |
+
top_crimes,
|
| 165 |
+
names="Crime Type",
|
| 166 |
+
values="Count",
|
| 167 |
+
hole=0.4,
|
| 168 |
+
color_discrete_sequence=px.colors.sequential.Agsunset,
|
| 169 |
+
title=" "
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
fig.update_traces(
|
| 173 |
+
textposition="outside",
|
| 174 |
+
textinfo="label+percent",
|
| 175 |
+
pull=[0.05] * len(top_crimes),
|
| 176 |
+
marker=dict(line=dict(color="white", width=2))
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
fig.update_layout(
|
| 180 |
+
legend_title_text="Crime Type",
|
| 181 |
+
margin=dict(t=60, b=20, l=20, r=20),
|
| 182 |
+
height=700,
|
| 183 |
+
title_x=0.5
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# Display the plot.
|
| 187 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 188 |
+
|
| 189 |
+
# Description.
|
| 190 |
+
st.markdown(""" The donut chart shows the share of the ten most frequent crime categories in the selected year. At the center, you can see that Vehicle – Stolen is the single largest slice, accounting for roughly 18.7% of all incidents, The remaining five categories each represent between 3%–5% of total incidents—these include miscellaneous crimes, criminal threats, assault with a deadly weapon, burglary, and minor vandalism. By displaying both slice size and percentage labels, the chart makes it easy to compare how dominant property‐related offenses are, versus violent or lesser‐common crimes, in that year’s LAPD data. """)
|
| 191 |
|
| 192 |
|
| 193 |
# -------------------------------- Plot 2: Heat Map --------------------------------
|
| 194 |
+
elif page == "Heat Map":
|
| 195 |
+
# Count the crime type and list out the top 10 crime type that have the most cases.
|
| 196 |
+
top_crimes = df['crm_cd_desc'].value_counts().nlargest(10).index
|
| 197 |
+
df_top = df[df['crm_cd_desc'].isin(top_crimes)]
|
| 198 |
+
|
| 199 |
+
# Group by crime type and year.
|
| 200 |
+
heatmap1_data = df_top.groupby(['crm_cd_desc', 'year']).size().unstack(fill_value=0)
|
| 201 |
+
|
| 202 |
+
# Create the heat map.
|
| 203 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 204 |
+
|
| 205 |
+
# 2. Draw into that Axes
|
| 206 |
+
sns.heatmap(
|
| 207 |
+
heatmap1_data,
|
| 208 |
+
annot=True,
|
| 209 |
+
fmt="d",
|
| 210 |
+
cmap="YlOrRd",
|
| 211 |
+
ax=ax
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
# 3. Set titles/labels on the Axes
|
| 215 |
+
ax.set_title("Top 10 Crime Types by Year")
|
| 216 |
+
ax.set_xlabel("Year")
|
| 217 |
+
ax.set_ylabel("Crime Type")
|
| 218 |
+
|
| 219 |
+
# 4. Tight layout
|
| 220 |
+
fig.tight_layout()
|
| 221 |
+
|
| 222 |
+
# 5. Render in Streamlit
|
| 223 |
+
st.pyplot(fig)
|
| 224 |
+
|
| 225 |
+
# Description.
|
| 226 |
+
st.markdown("""
|
| 227 |
+
This heatmap shows the frequency of the top 10 crimes from 2020 to 2025. The x axis is year and the y axis is crime type. The colormap is 'YlOrRd' to create a distinct visual difference in number of incidents. Dark red means that the incident frequency is high while light yellow means that the incident frequency is low. 'Vehicle Stolen' seems to be the most prevalent crime for all five years, given its values are highlighted in deeper shades of red. 'Vehicle Stolen' also seems to fluctuate between 20000 and 24000 throughout the five years. 'Thief of identity' also saw a spike in incident frequency for 2022, recording 21251 crimes. Limiting the heatmap to top 10 crimes addressed the most prominent crimes in LA. Since 2025 is not over, data for that year is still relatively inclusive. This visualization can help law enforcement easily detect trends of different crimes for a specific year. This data may allow them to predict future rates and be able to allocate resources accordingly to mitigate these crimes.
|
| 228 |
+
""")
|
| 229 |
|
| 230 |
|
| 231 |
# -------------------------------- Plot 3: Line Chart --------------------------------
|
| 232 |
+
elif page == "Line Chart":
|
| 233 |
+
# Filter out the year 2025 since it is not the end, so that the trend can't be see.
|
| 234 |
+
df = df[df['year'] != 2025]
|
| 235 |
+
|
| 236 |
+
# Group the each crime type by year.
|
| 237 |
+
yearly_crime_counts = (
|
| 238 |
+
df.groupby(["year", "crm_cd_desc"])
|
| 239 |
+
.size()
|
| 240 |
+
.reset_index(name="Count")
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
# Filter the crime types that have the most top 5 cases.
|
| 244 |
+
top5_crimes = df["crm_cd_desc"].value_counts().nlargest(5).index
|
| 245 |
+
filtered_crimes = yearly_crime_counts[yearly_crime_counts["crm_cd_desc"].isin(top5_crimes)]
|
| 246 |
+
|
| 247 |
+
# Plot the line plot.
|
| 248 |
+
line_chart = alt.Chart(filtered_crimes).mark_line(point=True).encode(
|
| 249 |
+
x=alt.X("year:O", title="Year"),
|
| 250 |
+
y=alt.Y("Count:Q", title="Number of Incidents"),
|
| 251 |
+
color=alt.Color("crm_cd_desc:N", title="Crime Type"),
|
| 252 |
+
tooltip=["year", "crm_cd_desc", "Count"]
|
| 253 |
+
).properties(
|
| 254 |
+
title="Yearly Trends of Top 5 Crime Types",
|
| 255 |
+
width=700,
|
| 256 |
+
height=400
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
# Display the plot.
|
| 260 |
+
line_chart
|
| 261 |
+
|
| 262 |
+
# Description.
|
| 263 |
+
st.markdown(""" This plot is a line chart visualizing the annual number of incidents for the top 5 most frequent crime types over a five-year period, from 2020 to 2024. Each line represents a distinct crime type, allowing for easy comparison of trends across different categories. The x-axis represents the year, the y-axis indicates the number of incidents, and a legend identifies the color corresponding to each specific crime type: Battery - Simple Assault, Burglary From Vehicle, Theft of Identity, Vandalism - Felony , and Vehicle - Stolen. The plot highlights the fluctuations and overall trajectories of these major crime categories across the years.""")
|
| 264 |
|
| 265 |
|
| 266 |
# -------------------------------- Plot 4: Map --------------------------------
|
| 267 |
+
elif page == "Map":
|
| 268 |
+
# Load the data.
|
| 269 |
+
with open(GEOJSON_PATH, "r", encoding="utf-8") as f:
|
| 270 |
+
geojson_data = json.load(f)
|
| 271 |
+
|
| 272 |
+
# Identify top 10 crime types
|
| 273 |
+
top_10_crimes = df['crm_cd_desc'].value_counts().nlargest(10).index.tolist()
|
| 274 |
|
| 275 |
+
# Filter the main DataFrame to include only top 10 crimes
|
| 276 |
+
df_top = df[df['crm_cd_desc'].isin(top_10_crimes)]
|
| 277 |
+
|
| 278 |
+
# Creat dropdown menu
|
| 279 |
+
years = sorted(df['year'].unique())
|
| 280 |
+
year_dropdown = st.selectbox("Year: ", years)
|
| 281 |
+
crime_dropdown = st.selectbox("Crime Type: ", top_10_crimes)
|
| 282 |
+
|
| 283 |
+
# Filter data.
|
| 284 |
+
df_filtered = df[(df['year'] == year_dropdown) & (df['crm_cd_desc'] == crime_dropdown)].sample(n=300, random_state=1)
|
| 285 |
+
|
| 286 |
+
# Create the new folium map to make the map more interactive.
|
| 287 |
+
# Method comes from: https://folium.streamlit.app/.
|
| 288 |
+
new_map = folium.Map(location=[df_filtered['lat'].mean(), df_filtered['lon'].mean()], zoom_start=10)
|
| 289 |
+
|
| 290 |
+
# Add county boundary
|
| 291 |
+
folium.GeoJson(geojson_data, name="County Boundaries").add_to(new_map)
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
# # Create the map.
|
| 294 |
# def crime_map(year, crime):
|
|
|
|
| 311 |
# # Call the function with selected values
|
| 312 |
# crime_map(year_dropdown, crime_dropdown)
|
| 313 |
|
| 314 |
+
# Using for-loop to add the crime points
|
| 315 |
+
for _, row in df_filtered.iterrows():
|
| 316 |
+
folium.CircleMarker(
|
| 317 |
+
location=[row['lat'], row['lon']],
|
| 318 |
+
radius=3,
|
| 319 |
+
color='red',
|
| 320 |
+
fill=True,
|
| 321 |
+
fill_opacity=0.6,
|
| 322 |
+
popup=row['crm_cd_desc']
|
| 323 |
+
).add_to(new_map)
|
| 324 |
+
|
| 325 |
+
# Display the new map.
|
| 326 |
+
st_folium(new_map, width=1000, height=800)
|
| 327 |
+
|
| 328 |
+
# Description.
|
| 329 |
+
st.markdown("""
|
| 330 |
+
This visualization uses Folium to build an interactive map of crime distribution in Los Angeles, highlighting the geospatial clustering characteristics of different years and crime types, and emphasizing the user's experience of freely exploring the map. The base map uses real streets and geographic backgrounds to enhance the spatial visualization of the image. The map shows the administrative boundaries of Los Angeles County in blue polygons, which are loaded with GeoJSON data and overlaid on the map to specify the geographic boundaries of crime locations. The red dots on the map represent the location of individual crimes, and the system samples no more than 300 data items from this category for visualization, with each dot pinpointed by latitude and longitude coordinates. The map supports full Leaflet.js functionality, including zooming, dragging, layer control, and other operations, which greatly enhances the flexibility of data exploration. A drop-down menu in the upper left corner of the page allows users to customize filters for specific years and crime types, enabling instant updates to the map content.
|
| 331 |
+
""")
|
| 332 |
|
| 333 |
# -------------------------------- Plot 4: Stacked Bar Chart --------------------------------
|
| 334 |
+
elif page == "Stacked Bar Chart":
|
| 335 |
+
# Group by crime type and year.
|
| 336 |
+
stacked_year_df = df_top.groupby(['year', 'crm_cd_desc']).size().reset_index(name='count')
|
| 337 |
+
|
| 338 |
+
# Create the stacked bar chart.
|
| 339 |
+
bar_chart = alt.Chart(stacked_year_df).mark_bar().encode(
|
| 340 |
+
x=alt.X('year:O', title='Year'),
|
| 341 |
+
y=alt.Y('count:Q', stack='zero', title='Number of Incidents'),
|
| 342 |
+
color=alt.Color('crm_cd_desc:N', title='Crime Type'),
|
| 343 |
+
tooltip=['year', 'crm_cd_desc', 'count']
|
| 344 |
+
).properties(
|
| 345 |
+
width=600,
|
| 346 |
+
height=400,
|
| 347 |
+
title='Stacked Crime Composition by Year (Top 10 Crime Types)'
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
# Display the plot.
|
| 351 |
+
st.altair_chart(bar_chart, use_container_width=True)
|
| 352 |
+
|
| 353 |
+
# Description.
|
| 354 |
+
st.markdown("""
|
| 355 |
+
Description: Our stacked bar chart shows the number of reported crimes for the top 10 most common crime types from 2020 to 2024. Each bar represents a year, and the different colors in the bars show different types of crimes, like stolen vehicles, burglary, vandalism, and assault. The taller the colored section, the more incidents of that crime there were in that year.
|
| 356 |
+
|
| 357 |
+
By observing the plot, we can find out that 2022 had the most crimes, the year had the second most crimes is 2023, and etc. Besides that, we can also find out that some crimes, like vehicle theft, petty theft, and burglary from vehicles, happened a lot every year and make up a big part of the total.
|
| 358 |
+
""")
|
| 359 |
|
| 360 |
# -------------------------------- Plot 5: Bar Chart --------------------------------
|
| 361 |
+
elif page == "Bar Chart":
|
| 362 |
+
# Group by crime type and year.
|
| 363 |
+
heatmap1_df = df_top.groupby(['crm_cd_desc', 'year']).size().reset_index(name='count')
|
| 364 |
+
|
| 365 |
+
# Create the slider based on the previous heatmap.
|
| 366 |
+
year_slider = alt.binding_range(min=heatmap1_df['year'].min(), max=heatmap1_df['year'].max(), step=1)
|
| 367 |
+
year_select = alt.selection_point(fields=['year'], bind=year_slider, value = 2022, name="Select")
|
| 368 |
+
|
| 369 |
+
# Convert the heatmap into bar chart.
|
| 370 |
+
barchart = alt.Chart(heatmap1_df).mark_bar().encode(
|
| 371 |
+
x=alt.X('crm_cd_desc:N', title='Crime Type', sort='-y'),
|
| 372 |
+
y=alt.Y('count:Q', title='Number of Incidents'),
|
| 373 |
+
color=alt.Color('crm_cd_desc:N', title='Crime Type'),
|
| 374 |
+
tooltip=['crm_cd_desc', 'count']
|
| 375 |
+
).transform_filter(
|
| 376 |
+
year_select
|
| 377 |
+
).add_params(
|
| 378 |
+
year_select
|
| 379 |
+
).properties(
|
| 380 |
+
width=600,
|
| 381 |
+
height=400,
|
| 382 |
+
title='Top 10 Crime Types (Filtered by Year)'
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
# Display the plot.
|
| 386 |
+
barchart
|
| 387 |
+
|
| 388 |
+
# Description.
|
| 389 |
+
st.markdown(""" This interactive bar chart allows users to explore the most frequently reported crime types in Los Angeles by year. By adjusting the slider below the chart, the visualization updates in real time to show the top ten crime categories for the selected year. Each bar represents the total number of incidents, with color coding used to distinguish different crime types and a legend on the right for reference.
|
| 390 |
+
This visualization makes it easy to compare how the composition of major crime types evolves over time and to detect emerging issues that may require further investigation or policy response.
|
| 391 |
+
""")
|