# 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(""" """, unsafe_allow_html=True) # 1. Page title st.markdown("

🚔 Crime Pulse: LAPD Incident Explorer 🔎

", unsafe_allow_html=True) st.markdown("

Group 9: Vighnesh Gosavi, Vivian Lin, Chun-Wen Liou, Shivam Patel, Jinwen Zhang

", unsafe_allow_html=True) 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.
""",unsafe_allow_html=True) # 2. Data info & load st.markdown("
Dataset Information
", unsafe_allow_html=True) st.markdown( """
""", 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("
Data Preview
", unsafe_allow_html=True) st.markdown( f"
" f"Total records: {df.shape[0]:,}  |  " f"Total columns: {df.shape[1]:,}" f"
", unsafe_allow_html=True ) st.dataframe(df.head()) # Pie Chart 1: Top 10 Crime Types st.markdown("
Top 10 Crime Types by Year
", 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("""
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.
""",unsafe_allow_html=True) # -------------------------------- Plot : Bubble Map of Incident Counts by Region -------------------------------- # st.markdown("
Crime Hotspots by Region
", 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("
Crime Composition by Region: Top 5 Offenses
", 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("""
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.
""",unsafe_allow_html=True) # -------------------------------- Plot 3: Line Chart for Incident Counts by Region -------------------------------- st.markdown("
Incidents Trends over Time
", 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("""
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.
""",unsafe_allow_html=True) # -------------------------------- Plot : Bubble Map of Incident Counts by Region NO MAP -------------------------------- # st.markdown("
Crime Hotspots by Region NO MAP
", 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("
HeatMap
", 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("""
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.
""",unsafe_allow_html=True) # -------------------------------- Plot 5: Line Chart -------------------------------- st.markdown("
Line Chart
", 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("""
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.
""",unsafe_allow_html=True) # -------------------------------- Plot 6: Map -------------------------------- st.markdown("
Explore LA Crime Patterns: An Interactive Folium Map
", 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("""
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.
""",unsafe_allow_html=True) # -------------------------------- Plot 7: Stacked Bar Chart -------------------------------- st.markdown("
Trends in Top 10 Crime Types (2020–2024)
", 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("""
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.
""",unsafe_allow_html=True) # -------------------------------- Plot 8: Bar Chart -------------------------------- st.markdown("
Crime Rankings for Selected Year
", 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("""
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.
""",unsafe_allow_html=True) st.markdown("

Reference: LAPD Crime Data

", unsafe_allow_html=True)