File size: 25,739 Bytes
7be56db
49ae60f
258960e
a290e78
414053c
a290e78
 
 
414053c
0f82f11
 
ab73d83
30fc316
 
6870e43
d14c914
414053c
30fc316
 
 
49ae60f
5dd4d2e
7783047
 
5dd4d2e
 
7783047
5dd4d2e
 
 
 
 
 
7783047
a290e78
572bd34
7e2295c
7e79ca0
b1bba95
 
 
 
 
 
 
 
 
 
64f90bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1bba95
 
 
64f90bb
 
8c8bd2c
bbc6d5d
7e79ca0
64f90bb
 
 
 
 
 
b1bba95
64f90bb
b1bba95
64f90bb
 
 
 
 
 
 
 
 
 
 
b1bba95
a290e78
7e79ca0
 
 
7783047
7e79ca0
 
 
 
 
 
a290e78
7e79ca0
 
a290e78
b1bba95
 
 
572bd34
 
7e79ca0
64f90bb
7e79ca0
 
 
b1bba95
2456bcb
572bd34
 
 
 
2456bcb
 
572bd34
 
 
 
 
b1bba95
64f90bb
 
 
 
 
 
 
 
b1bba95
7e79ca0
b1bba95
64f90bb
b1bba95
 
 
 
64f90bb
 
 
 
 
 
 
 
 
 
b1bba95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a290e78
30fc316
7e79ca0
b1bba95
 
 
 
 
 
 
 
 
 
 
 
64f90bb
 
b1bba95
 
 
 
64f90bb
 
 
b1bba95
 
 
 
 
 
 
6ae230d
 
 
 
 
30fc316
6b3ed66
3ed582d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bd5abd
6b3ed66
3ed582d
41aee1f
 
 
 
 
 
 
 
 
 
 
 
cc94f55
41aee1f
 
 
 
 
 
 
 
a169bc5
41aee1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c56cb
 
 
 
 
 
8f9f24e
6b3ed66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f9f24e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3523535
6b3ed66
5b705ba
b1bba95
 
 
 
 
 
 
 
8c8bd2c
b1bba95
 
 
 
 
 
 
b7140d3
 
 
b1bba95
 
882a2b3
b194a7c
 
 
882a2b3
 
 
 
b1bba95
 
 
 
 
 
 
 
5b705ba
b1bba95
22785ba
865605f
30fc316
6b3ed66
5b705ba
b1bba95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b705ba
 
 
 
 
22785ba
1535d87
30fc316
6b3ed66
a169bc5
b1bba95
 
 
7e79ca0
b1bba95
 
9565121
b1bba95
 
7e79ca0
b1bba95
 
 
 
7e79ca0
b1bba95
 
7e79ca0
b1bba95
 
 
7e79ca0
b1bba95
 
cfee38a
 
 
 
 
 
 
 
 
65c418c
cfee38a
 
 
 
 
 
 
 
 
 
 
 
b1bba95
 
 
 
 
 
 
 
 
 
 
 
5a5042d
b1bba95
 
22785ba
b1bba95
22785ba
cade28d
6b3ed66
a169bc5
b1bba95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22785ba
b1bba95
 
 
22785ba
3c95e1f
6b3ed66
a169bc5
b1bba95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22785ba
b1bba95
573d47b
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# Imports.
import streamlit as st
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import altair as alt
from pathlib import Path
import plotly.express as px
import geopandas as gpd
import folium
from streamlit_folium import st_folium
import json
import os
from pathlib import Path
import circlify
import plotly.graph_objects as go

# point Streamlit at a writable folder
os.environ["STREAMLIT_CONFIG_DIR"] = "/tmp/.streamlit"
Path(os.environ["STREAMLIT_CONFIG_DIR"]).mkdir(parents=True, exist_ok=True)


# Define paths.
# Path for geo_json.
GEOJSON_PATH = Path(__file__).parent / "County_Boundary.geojson"

# Handle the error for geo_json.
try:
    gdf_counties = gpd.read_file(GEOJSON_PATH)
except FileNotFoundError:
    st.error("Error: 'County_Boundary.geojson' file not found in the /app/src/ directory. Please ensure the file is included in the project.")
    st.stop()

# Path for crime data.
DATA_PATH = Path(__file__).parent / "crime_data.csv"        # /app/src/crime_data.csv
REGION_DATA_PATH = Path(__file__).parent / "area_lookup.csv"

# ── 0. Page configuration ──
st.set_page_config(
    page_title="Analyze Crime Distributions", 
    page_icon="📊", 
    layout="wide"
)
st.markdown("""
        <style>
        .title {
            text-align: center;
            padding: 25px;
            color: #2c3e50;
            font-family: 'Source Sans Pro', sans-serif;
        }
        /* Paragraph/write-up styling */
      .description {
        font-size: 18px;           /* comfortable reading size */
        line-height: 1.6;          /* good spacing */
        color: #4b4b4b;            /* dark grey text */
        text-align: justify;       /* nice full-justified look */
        padding: 0 10px 20px;      /* side & bottom padding */
        font-family: 'Helvetica Neue', Arial, sans-serif;
      }
      .sectionheader {
          font-family: 'Source Sans Pro', sans-serif;
          font-size: 32px;
          color: #2c3e50;
          margin-top: 15px;
          margin-bottom: 10px;
          border-bottom: 3px solid #ccc;
          padding-bottom: 8px;
        }
        </style>
        """, unsafe_allow_html=True)

# 1. Page title
st.markdown("<div class='title'><h1> 🚔 Crime Pulse: LAPD Incident Explorer 🔎 </h1></div>", unsafe_allow_html=True)
st.markdown("<div class='title'><h3>Group 9: Vighnesh Gosavi, Vivian Lin, Chun-Wen Liou, Shivam Patel, Jinwen Zhang</h3></div>", unsafe_allow_html=True)
    
st.markdown("""<div class='description'> 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.</div>""",unsafe_allow_html=True)

# 2. Data info & load
st.markdown("<div class='sectionheader'> Dataset Information </div>", unsafe_allow_html=True)
st.markdown(
    """
    <div class="description">
      <ul>
        <li><strong>Source:</strong> LAPD crime incidents dataset</li>
        <li><strong>Rows:</strong> one incident per row</li>
        <li><strong>Columns:</strong> e.g. <code>crm_cd_desc</code> (crime type), <code>arrest</code> (boolean), <code>year</code>, <code>location_description</code>, etc.</li>
        <li><strong>Purpose:</strong> Interactive exploration of top crime categories and arrest rates.</li>
      </ul>
    </div>
    """,
    unsafe_allow_html=True
)

# # Define paths.
# # Path for geo_json.
# GEOJSON_PATH = Path(__file__).parent / "County_Boundary.geojson"

# # Handle the error for geo_json.
# try:
#     gdf_counties = gpd.read_file(GEOJSON_PATH)
# except FileNotFoundError:
#     st.error("Error: 'County_Boundary.geojson' file not found in the /app/src/ directory. Please ensure the file is included in the project.")
#     st.stop()

# # Path for crime data.
# DATA_PATH = Path(__file__).parent / "crime_data.csv"        # /app/src/crime_data.csv

@st.cache_data
def load_data():
    return pd.read_csv(DATA_PATH)
def region_load_data():
    return pd.read_csv(REGION_DATA_PATH)    
    
if st.button("🔄 Refresh Data"):
        st.cache_data.clear()  # Clear the cache
        st.toast("Data is refreshed",icon="✅")  # Reload the data
        
# 2. Load and early‐exit if missing
df = load_data()
lookup = region_load_data()
map_region   = dict(zip(lookup["OBJECTID"], lookup["APREC"]))
map_precinct = dict(zip(lookup["OBJECTID"], lookup["PREC"]))

if df.empty:
    st.stop()

# Map into new columns
df["RegionName"]   = df["area"].map(map_region)
df["PrecinctCode"] = df["area"].map(map_precinct)

# 3. Data preview
st.markdown("<div class='sectionheader'> Data Preview </div>", unsafe_allow_html=True)
st.markdown(
    f"<div class='description'>"
    f"Total records: <strong>{df.shape[0]:,}</strong> &nbsp;|&nbsp; "
    f"Total columns: <strong>{df.shape[1]:,}</strong>"
    f"</div>",
    unsafe_allow_html=True
)
st.dataframe(df.head())

# Pie Chart 1: Top 10 Crime Types
st.markdown("<div class='sectionheader'> Top 10 Crime Types by Year </div>", unsafe_allow_html=True)
    
years = sorted(df["year"].dropna().astype(int).unique())
# Prepend an “All” option
options = ["All"] + years
selected_year = st.selectbox("Select Year", options, index=0)    
# # Year filter (shorter, above chart)
# col_empty, col_filter = st.columns([3,1])
# with col_filter:
#     selected_year = st.selectbox(
#         "Select Year",
#         options=options,
#         index=0,  # default to “All”
#         key="year_filter"
#     )
    
# Filter according to selection
if selected_year == "All":
    filtered = df.copy()
else:
    filtered = df[df["year"] == selected_year]
    
# Compute top 10 crime types for that year ──
top_crimes = (
    filtered["crm_cd_desc"]
        .value_counts()
        .nlargest(10)
        .rename_axis("Crime Type")
        .reset_index(name="Count")
)
top_crimes["Percentage"] = top_crimes["Count"] / top_crimes["Count"].sum()
    
#Key Metrics
st.markdown("### Key Metrics", unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
col1.metric(
    label="Total Incidents",
    value=f"{len(filtered):,}"
)
col2.metric(
    label="Unique Crime Types",
    value=f"{filtered['crm_cd_desc'].nunique():,}"
)
# compute share of the top crime
top_share = top_crimes.iloc[0]["Percentage"]  
col3.metric(
    label=f"Share of Top Crime ({top_crimes.iloc[0]['Crime Type']})",
    value=f"{top_share:.1%}"
)


# -------------------------------- Plot 1: Pie(Donut) Chart --------------------------------
fig = px.pie(
    top_crimes,
    names="Crime Type",
    values="Count",
    hole=0.4,
    color_discrete_sequence=px.colors.sequential.Agsunset,
    title="  "
)
    
fig.update_traces(
    textposition="outside",
    textinfo="label+percent",
    pull=[0.02] * len(top_crimes),
    marker=dict(line=dict(color="white", width=1))
)
    
fig.update_layout(
    legend_title_text="Crime Type",
    margin=dict(t=40, b=40, l=20, r=20),
    height=600,
    width=450,
    title_x=0.5
)
    
# Display the plot.
st.plotly_chart(fig, use_container_width=True)
    
# Description.
st.markdown("""<div class="description"> The donut chart elegantly shows how ten key crime categories divide the incidents for the selected year into distinct slices. 
Circular rings highlight property crimes especially vehicle theft as the most common offenses, while smaller wedges represent less frequent incidents such as vandalism, 
criminal threats and minor burglary. Violent acts such as simple assault and robbery occupy medium sized segments, creating a clear visual hierarchy of frequency without 
relying on specific numbers. By pairing each slice with its label, the chart provides an immediate intuitive understanding of which crime types contribute most to overall 
volume and which are comparatively rare, helping stakeholders focus on the offenses that matter most.</div>""",unsafe_allow_html=True)

# -------------------------------- Plot : Bubble Map of Incident Counts by Region --------------------------------
# st.markdown("<div class='sectionheader'>Crime Hotspots by Region</div>", unsafe_allow_html=True)

# # 1. Aggregate counts and centroids
# region_stats = (
#     df
#       .groupby("RegionName")
#       .agg(
#           Count   = pd.NamedAgg(column="crm_cd_desc", aggfunc="size"),
#           Latitude  = pd.NamedAgg(column="lat", aggfunc="mean"),
#           Longitude = pd.NamedAgg(column="lon", aggfunc="mean")
#       )
#       .reset_index()
# )

# # 2. Build the bubble map
# fig = px.scatter_mapbox(
#     region_stats,
#     lat="Latitude",
#     lon="Longitude",
#     size="Count",                       # bubble size ~ incident volume
#     color="Count",                      # color gradient for emphasis
#     hover_name="RegionName",
#     hover_data={"Count":True, "Latitude":False, "Longitude":False},
#     size_max=30,                        # max bubble diameter
#     zoom=10,                            # adjust to focus your city
#     mapbox_style="open-street-map",
#     title="Crime Volume by Region (Bubble Map)"
# )

# # 3. Tidy layout
# fig.update_layout(
#     margin=dict(t=50, b=0, l=0, r=0),
#     legend_title_text="Incident Count",
#     title_x=0.5
# )

# # 4. Render
# st.plotly_chart(fig, use_container_width=True)

# -------------------------------- Plot 2: Stacked Bar Charts for Regions --------------------------------
st.markdown("<div class='sectionheader'>Crime Composition by Region: Top 5 Offenses </div>", unsafe_allow_html=True)
# 1. Compute counts per region and crime
counts = (
    df
    .groupby(['RegionName', 'crm_cd_desc'])
    .size()
    .reset_index(name='Count')
)

# 2. For each region, keep only its top 5 crime types
top5_per_region = (
    counts
    .groupby('RegionName', group_keys=False)
    .apply(lambda grp: grp.nlargest(5, 'Count'))
)

# 3. Draw a stacked bar chart
fig = px.bar(
    top5_per_region,
    x='RegionName',
    y='Count',
    color='crm_cd_desc',
    color_discrete_sequence=px.colors.sequential.Agsunset,
    title='Top 5 Crimes by Region',
    labels={'crm_cd_desc': 'Crime Type'},
    height=600
)

# 4. Tweak layout for readability
fig.update_layout(
    barmode='stack', 
    xaxis_tickangle=-45,
    xaxis_title='', 
    yaxis_title='Incident Count',
    legend_title_text='Crime Type',
    margin=dict(t=50, b=150, l=50, r=50)
)

# 5. Render in Streamlit
st.plotly_chart(fig, use_container_width=True)
# Description.
st.markdown("""<div class="description"> This stacked‐bar chart breaks down each region’s crime profile by its five most common offenses. The bars’ 
layers show how certain neighborhoods are dominated by property crimes (like vehicle theft and petty theft), whereas others carry a heavier share of 
violent or specialty offenses. By grouping all five slices together, the visualization highlights both the volume and mix of crimes in each area—revealing, 
for example, precincts where assault plays a disproportionately large role versus those driven mainly by theft. This makes it straightforward to compare how 
offense patterns differ from one region to the next.</div>""",unsafe_allow_html=True)

# -------------------------------- Plot 3: Line Chart for Incident Counts by Region --------------------------------
st.markdown("<div class='sectionheader'>Incidents Trends over Time </div>", unsafe_allow_html=True)
# 1. Aggregate total incidents by year
yearly_region = (
    df
      .groupby(["year", "RegionName"])
      .size()
      .reset_index(name="Count")
)

# 2. Let the user pick one region to highlight
regions = sorted(yearly_region["RegionName"].unique())
sel_region = st.selectbox("Select Region", ["All"] + regions, index=0)

if sel_region != "All":
    yearly_region = yearly_region[yearly_region["RegionName"] == sel_region]

# 3. Plot a smooth line per region (or just the one selected)
fig = px.line(
    yearly_region,
    x="year",
    y="Count",
    color="RegionName",
    title=(" "),
    labels={"year":"Year", "Count":"Incident Count"}
)

# 4. Add LOWESS smoothing (optional)
for trace in fig.data:
    trace.update(mode="lines")  # remove markers

st.plotly_chart(fig, use_container_width=True)
# Description.
st.markdown("""<div class="description"> This multi‐line chart tracks how total crime incidents have evolved across LAPD regions from 2020 
through 2025. Each colored line represents a different precinct, letting you compare their trajectories side by side. You’ll notice that most 
areas rose to a peak around 2022 before tapering off, while a handful of regions bucked the trend—either holding steady or dipping earlier. The 
clear visual of converging and diverging lines makes it easy to spot which precincts saw the sharpest upticks, which managed to keep incidents 
relatively flat, and how the overall pattern shifted over the five‐year span.</div>""",unsafe_allow_html=True)



# -------------------------------- Plot : Bubble Map of Incident Counts by Region NO MAP --------------------------------
# st.markdown("<div class='sectionheader'>Crime Hotspots by Region NO MAP</div>", unsafe_allow_html=True)

# # 1. Aggregate total incidents by region and pick top 10
# region_counts = (
#     df
#       .groupby("RegionName")            # group by your text field
#       .size()                           # count rows
#       .reset_index(name="Count")        # turn it into a DataFrame with columns RegionName & Count
# )
# top_regions = region_counts.head(10)
# # 2. Build the bubble chart
# fig = px.scatter(
#     top_regions,
#     x='Count',
#     y='RegionName',
#     size='Count',               # bubble area ∝ incident count
#     color='Count',              # color scale also shows volume
#     hover_name='RegionName',        # show region on hover
#     hover_data={'Count':True},
#     size_max=60,                # max bubble diameter
#     title='Top 10 Regions by Crime Volume (Bubble Chart)'
# )

# # 3. Tweak layout
# fig.update_layout(
#     xaxis_tickangle=-45,        # tilt x-labels so they’re legible
#     margin=dict(t=50, b=100),
#     yaxis_title='Incident Count',
#     xaxis_title=''
# )

# # 4. Render in Streamlit
# st.plotly_chart(fig, use_container_width=True)

# -------------------------------- Plot 4: Heat Map --------------------------------
st.markdown("<div class='sectionheader'> HeatMap </div>", unsafe_allow_html=True)
# Count the crime type and list out the top 10 crime type that have the most cases.
top_crimes = df['crm_cd_desc'].value_counts().nlargest(10).index
df_top = df[df['crm_cd_desc'].isin(top_crimes)]
    
# Group by crime type and year.
heatmap1_data = df_top.groupby(['crm_cd_desc', 'year']).size().unstack(fill_value=0)
    
# Create the heat map.
fig, ax = plt.subplots(figsize=(8, 4))
    
# 2. Draw into that Axes
sns.heatmap(
    heatmap1_data,
    annot=True,
    fmt="d",
    cmap="YlOrRd",
    ax=ax,
    annot_kws={"size": 6},               # smaller numbers in cells
    cbar_kws={"shrink": 0.5}             # shrink the colorbar
)
    
# 3. Set titles/labels with a smaller font
ax.set_title("Top 10 Crime Types by Year", fontsize=10, pad=8)
ax.set_xlabel("Year", fontsize=8, labelpad=6)
ax.set_ylabel("Crime Type", fontsize=8, labelpad=6)

# Shrink the tick labels
ax.tick_params(axis='x', labelsize=10, rotation=0)  # no rotation, smaller font
ax.tick_params(axis='y', labelsize=10)              # smaller font
    
# 4. Tight layout
fig.tight_layout()
    
# 5. Render in Streamlit
st.pyplot(fig)
    
# Description.
st.markdown("""<div class="description">
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.
</div>""",unsafe_allow_html=True)


# -------------------------------- Plot 5: Line Chart --------------------------------
st.markdown("<div class='sectionheader'> Line Chart </div>", unsafe_allow_html=True)
# Filter out the year 2025 since it is not the end, so that the trend can't be see.
df = df[df['year'] != 2025]
    
# Group the each crime type by year.
yearly_crime_counts = (
    df.groupby(["year", "crm_cd_desc"])
    .size()
    .reset_index(name="Count")
)
    
# Filter the crime types that have the most top 5 cases.
top5_crimes = df["crm_cd_desc"].value_counts().nlargest(5).index
filtered_crimes = yearly_crime_counts[yearly_crime_counts["crm_cd_desc"].isin(top5_crimes)]
    
# Plot the line plot.
line_chart = alt.Chart(filtered_crimes).mark_line(point=True).encode(
    x=alt.X("year:O", title="Year"),
    y=alt.Y("Count:Q", title="Number of Incidents"),
    color=alt.Color("crm_cd_desc:N", title="Crime Type"),
    tooltip=["year", "crm_cd_desc", "Count"]
).properties(
    title="Yearly Trends of Top 5 Crime Types",
    width=700,  
    height=400
)
    
# Display the plot.
line_chart
    
# Description.
st.markdown("""<div class="description">
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.</div>""",unsafe_allow_html=True)


# -------------------------------- Plot 6: Map --------------------------------
st.markdown("<div class='sectionheader'> Explore LA Crime Patterns: An Interactive Folium Map </div>", unsafe_allow_html=True)
# Load the data.
with open(GEOJSON_PATH, "r", encoding="utf-8") as f:
    geojson_data = json.load(f)
        
# Identify top 10 crime types
top_10_crimes = df['crm_cd_desc'].value_counts().nlargest(10).index.tolist()
    
# Filter the main DataFrame to include only top 10 crimes
df_top = df[df['crm_cd_desc'].isin(top_10_crimes)]
    
# Creat dropdown menu
years = sorted(df['year'].unique())
year_dropdown = st.selectbox("Year: ", years)
crime_dropdown = st.selectbox("Crime Type: ", top_10_crimes)
    
# Filter data.
df_filtered = df[(df['year'] == year_dropdown) & (df['crm_cd_desc'] == crime_dropdown)].sample(n=300, random_state=1)
    
# Create the new folium map to make the map more interactive.
# Method comes from: https://folium.streamlit.app/.
new_map = folium.Map(location=[df_filtered['lat'].mean(), df_filtered['lon'].mean()], zoom_start=10)
    
# Add county boundary
folium.GeoJson(geojson_data, name="County Boundaries").add_to(new_map)

# # Create the map.
# def crime_map(year, crime):
#     df_filtered = df[(df['year'] == year) & (df['crm_cd_desc'] == crime)].sample(n=300, random_state=1)
#     gdf_points = gpd.GeoDataFrame(
#         df_filtered,
#         geometry=gpd.points_from_xy(df_filtered['lon'], df_filtered['lat']),
#         crs="EPSG:4326"
#     )
    
#     fig, ax = plt.subplots(figsize=(10, 10))
#     gdf_counties.plot(ax=ax, color='lightgray', edgecolor='white')
#     gdf_points.plot(ax=ax, color='red', markersize=10, alpha=0.6)
#     ax.set_title(f"{crime} - {year}")
#     ax.set_xlabel("Longitude")
#     ax.set_ylabel("Latitude")
#     plt.grid(True)
#     st.pyplot(fig)

# # Call the function with selected values
# crime_map(year_dropdown, crime_dropdown)

# Using for-loop to add the crime points
for _, row in df_filtered.iterrows():
    folium.CircleMarker(
        location=[row['lat'], row['lon']],
        radius=3,
        color='red',
        fill=True,
        fill_opacity=0.6,
        popup=row['crm_cd_desc']
    ).add_to(new_map)
    
# Display the new map.
st_folium(new_map, width=1000, height=500, use_container_width=True)
    
# Description.
st.markdown("""<div class="description">
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.
</div>""",unsafe_allow_html=True)

# -------------------------------- Plot 7: Stacked Bar Chart --------------------------------
st.markdown("<div class='sectionheader'>Trends in Top 10 Crime Types (2020–2024)</div>", unsafe_allow_html=True)
# Group by crime type and year.
stacked_year_df = df_top.groupby(['year', 'crm_cd_desc']).size().reset_index(name='count')
    
# Create the stacked bar chart.
bar_chart = alt.Chart(stacked_year_df).mark_bar().encode(
    x=alt.X('year:O', title='Year'),
    y=alt.Y('count:Q', stack='zero', title='Number of Incidents'),
    color=alt.Color('crm_cd_desc:N', title='Crime Type'),
    tooltip=['year', 'crm_cd_desc', 'count']
).properties(
    width=600,
    height=400,
    title='Stacked Crime Composition by Year (Top 10 Crime Types)'
)
    
# Display the plot.
st.altair_chart(bar_chart, use_container_width=True)
    
# Description.
st.markdown("""<div class="description">
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.
    
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.
</div>""",unsafe_allow_html=True)

# -------------------------------- Plot 8: Bar Chart --------------------------------
st.markdown("<div class='sectionheader'>Crime Rankings for Selected Year</div>", unsafe_allow_html=True)
# Group by crime type and year.
heatmap1_df = df_top.groupby(['crm_cd_desc', 'year']).size().reset_index(name='count')
    
# Create the slider based on the previous heatmap.
year_slider = alt.binding_range(min=heatmap1_df['year'].min(), max=heatmap1_df['year'].max(), step=1)
year_select = alt.selection_point(fields=['year'], bind=year_slider, value = 2022, name="Select")
    
# Convert the heatmap into bar chart.
barchart = alt.Chart(heatmap1_df).mark_bar().encode(
    x=alt.X('crm_cd_desc:N', title='Crime Type', sort='-y'),
    y=alt.Y('count:Q', title='Number of Incidents'),
    color=alt.Color('crm_cd_desc:N', title='Crime Type'),
    tooltip=['crm_cd_desc', 'count']
).transform_filter(
    year_select
).add_params(
    year_select
).properties(
    width=600,
    height=400,
    title='Top 10 Crime Types (Filtered by Year)'
)
    
# Display the plot.
barchart
    
# Description.
st.markdown("""<div class="description"> 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.
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.
</div>""",unsafe_allow_html=True)

st.markdown("<div class='title'><h4>Reference: LAPD Crime Data</h4></div>", unsafe_allow_html=True)