wanwanlin0521 commited on
Commit
65c418c
·
verified ·
1 Parent(s): 4d12014

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +63 -0
src/streamlit_app.py CHANGED
@@ -184,6 +184,69 @@ menu = st.sidebar.selectbox(
184
  ["Home", "About", "Data", "Contact"]
185
  )
186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  # Define what each menu option does
188
  if menu == "Home":
189
  st.title("Analyze Crime Distributions")
 
184
  ["Home", "About", "Data", "Contact"]
185
  )
186
 
187
+ ### Use this one!!!
188
+ # Plot 3: Line chart.
189
+ df = df[df['year'] != 2025] # 2025 is not end, so the trend can't be see
190
+
191
+ # Group the each crime type by year.
192
+ yearly_crime_counts = (
193
+ df.groupby(["year", "crm_cd_desc"])
194
+ .size()
195
+ .reset_index(name="Count")
196
+ )
197
+
198
+ # Filter the crime types that have the most top 5 cases.
199
+ top5_crimes = df["crm_cd_desc"].value_counts().nlargest(5).index
200
+ filtered_crimes = yearly_crime_counts[yearly_crime_counts["crm_cd_desc"].isin(top5_crimes)]
201
+
202
+ # Plot the line plot.
203
+ line_chart = alt.Chart(filtered_crimes).mark_line(point=True).encode(
204
+ x=alt.X("year:O", title="Year"),
205
+ y=alt.Y("Count:Q", title="Number of Incidents"),
206
+ color=alt.Color("crm_cd_desc:N", title="Crime Type"),
207
+ tooltip=["year", "crm_cd_desc", "Count"]
208
+ ).properties(
209
+ title="Yearly Trends of Top 5 Crime Types",
210
+ width=700,
211
+ height=400
212
+ )
213
+
214
+ # Display the plot.
215
+ line_chart
216
+
217
+ ### Use this one!!!
218
+ # Identify top 10 crime types
219
+ top_10_crimes = df['crm_cd_desc'].value_counts().nlargest(10).index.tolist()
220
+
221
+ # Filter the main DataFrame to include only top 10 crimes
222
+ df_top = df[df['crm_cd_desc'].isin(top_10_crimes)]
223
+
224
+ # Create the dropdown.
225
+ crime_dropdown = ipywidgets.Dropdown(
226
+ options= sorted(top_10_crimes),
227
+ description="Crime Type:")
228
+
229
+ # Create the map.
230
+ def crime_map(year, crime):
231
+ df_filtered = df[(df['year'] == year) & (df['crm_cd_desc'] == crime)].sample(n=300, random_state=1)
232
+ gdf_points = gpd.GeoDataFrame(
233
+ df_filtered,
234
+ geometry=gpd.points_from_xy(df_filtered['lon'], df_filtered['lat']),
235
+ crs="EPSG:4326"
236
+ )
237
+
238
+ fig, ax = plt.subplots(figsize=(10, 10))
239
+ gdf_counties.plot(ax=ax, color='lightgray', edgecolor='white')
240
+ gdf_points.plot(ax=ax, color='red', markersize=10, alpha=0.6)
241
+ ax.set_title(f"{crime} - {year}")
242
+ ax.set_xlabel("Longitude")
243
+ ax.set_ylabel("Latitude")
244
+ plt.grid(True)
245
+ plt.show()
246
+
247
+ # Displat the plot.
248
+ ipywidgets.interact(crime_map, year=year_dropdown, crime=crime_dropdown)
249
+
250
  # Define what each menu option does
251
  if menu == "Home":
252
  st.title("Analyze Crime Distributions")