hyzhang00 commited on
Commit
15ca59b
·
verified ·
1 Parent(s): fc80154

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -24
app.py CHANGED
@@ -303,7 +303,53 @@ def create_category_distribution_chart(df, selected_category, selected_year):
303
  return fig
304
 
305
  def main():
306
- st.title('Traffic Crash Analysis')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
 
308
  # Load data
309
  df = load_and_preprocess_data('1.08_Crash_Data_Report_(detail).csv')
@@ -349,18 +395,40 @@ def main():
349
  years = sorted(df['Year'].unique())
350
  selected_year = st.selectbox('Select Year:', years)
351
 
352
- # Create and display map
353
- st.markdown("### Crash Location Map")
354
- map_placeholder = st.empty()
355
- with map_placeholder:
356
- m = create_map(df, selected_year)
357
- map_data = st_folium(
358
- m,
359
- width=800,
360
- height=600,
361
- key=f"map_{selected_year}",
362
- returned_objects=["null_drawing"]
363
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
 
365
  with tab3:
366
  # Weather condition filter
@@ -368,9 +436,38 @@ def main():
368
  selected_weather = st.selectbox('Select Weather Condition:', weather)
369
 
370
  # Create and display line graph
371
- st.markdown("### Crash Trend Over Time")
372
- trend_fig = create_crash_trend_chart(df, selected_weather)
373
- st.plotly_chart(trend_fig, use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
 
375
  with tab4:
376
  # Dropdown for Unit Type selection
@@ -382,10 +479,62 @@ def main():
382
  unit_type_pairs = sorted(list(unit_type_pairs))
383
  unit_type = st.selectbox("Select Unit Type Pair", options=['Total'] + unit_type_pairs)
384
 
385
- # Create 5th Visualization: Injuries and fatalities chart
386
- injuries_fatalities_chart = create_injuries_fatalities_chart(df, unit_type)
387
- st.altair_chart(injuries_fatalities_chart, use_container_width=True)
388
- st.markdown("#### TODO: add write-up for this 5th chart.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
 
390
  with tab5:
391
  # Dropdown for category selection
@@ -403,10 +552,31 @@ def main():
403
  years = ['All Years'] + sorted(df['Year'].dropna().unique().astype(int).tolist())
404
  selected_year = st.selectbox("Select Year:", years)
405
 
406
- # Generate and display the distribution chart
407
- st.markdown(f"### Distribution of Incidents by {selected_category}")
408
- distribution_chart = create_category_distribution_chart(df, selected_category, selected_year)
409
- st.plotly_chart(distribution_chart, use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
 
411
 
412
  if __name__ == "__main__":
 
303
  return fig
304
 
305
  def main():
306
+ st.set_page_config(page_title="Terrific Tempe Traffic", layout="wide")
307
+
308
+ st.markdown("""
309
+ <style>
310
+ .reportview-container {
311
+ font-size: 20px;
312
+ }
313
+ h1, h2, h3, h4, h5, h6 {
314
+ font-size: 150%;
315
+ }
316
+ p {
317
+ font-size: 125%;
318
+ }
319
+ </style>
320
+ """, unsafe_allow_html=True)
321
+
322
+
323
+ st.markdown("""
324
+ <style>
325
+ .title {
326
+ text-align: center;
327
+ padding: 25px;
328
+ }
329
+ </style>
330
+ """, unsafe_allow_html=True)
331
+
332
+ st.markdown("<div class='title'><h1> Accident Analysis for City of Tempe,Arizona </h1></div>", unsafe_allow_html=True)
333
+
334
+
335
+ st.markdown("""
336
+ **Team Members:**
337
+ - Janhavi Tushar Zarapkar ([email protected]
338
+ - Hangyue Zhang ([email protected])
339
+ - Andrew Nam ([email protected])
340
+ - Nirmal Attarde ([email protected])
341
+ - Maanas Sandeep Agrawa ([email protected])
342
+ """)
343
+
344
+
345
+ st.markdown("""
346
+ ### Introduction to the Traffic Accident Dataset
347
+ This dataset contains detailed information about traffic accidents in the city of **Tempe**. It includes various attributes of the accidents, such as the severity of injuries, the demographics of the drivers involved, the locations of the incidents, and the conditions at the time of the accidents. The dataset covers accidents that occurred over several years, with data on factors like **weather conditions**, **road surface conditions**, the **time of day**, and the type of **violations** (e.g., alcohol or drug use) that may have contributed to the accident.
348
+
349
+ The data was sourced from **Tempe City's traffic incident reports** and provides a comprehensive view of the factors influencing road safety and accident severity in the city. By analyzing this dataset, we can gain insights into the key contributors to traffic incidents and uncover trends that could help improve traffic safety measures, urban planning, and law enforcement policies in the city.
350
+ """)
351
+
352
+
353
 
354
  # Load data
355
  df = load_and_preprocess_data('1.08_Crash_Data_Report_(detail).csv')
 
395
  years = sorted(df['Year'].unique())
396
  selected_year = st.selectbox('Select Year:', years)
397
 
398
+ map_col, desc_col = st.columns([7, 3])
399
+
400
+ with map_col:
401
+ # Create and display map
402
+ st.markdown("### Crash Location Map")
403
+ map_placeholder = st.empty()
404
+ with map_placeholder:
405
+ m = create_map(df, selected_year)
406
+ map_data = st_folium(
407
+ m,
408
+ width=None,
409
+ height=800,
410
+ key=f"map_{selected_year}",
411
+ returned_objects=["null_drawing"]
412
+ )
413
+
414
+ with desc_col:
415
+ st.markdown("""
416
+ ### Traffic Crash Location Map
417
+ This interactive map visualizes traffic accidents in Tempe for the selected year. It combines **marker clustering** and a **heatmap** to show:
418
+ 1. **Accident Markers**: Red markers indicate individual accidents, with popups displaying the coordinates, date/time, and severity of each incident.
419
+ 2. **Heatmap**: The heatmap highlights accident hotspots with colors ranging from blue (low frequency) to yellow (moderate) and red (high frequency), showing areas with more frequent accidents.
420
+
421
+ **Key Features:**
422
+ * **Interactive Year Selection**: Users can select a year to view accidents for that specific time.
423
+ * **Accident Patterns**: The map reveals accident-prone areas and severity patterns, helping identify dangerous locations.
424
+
425
+ **Color Scheme:**
426
+ * **Red**: Individual accident markers.
427
+ * **Blue to Red**: Heatmap colors indicate accident frequency, from low (blue) to high (red).
428
+
429
+ This map provides insights into accident trends and can help guide safety improvements in the city.
430
+ """)
431
+
432
 
433
  with tab3:
434
  # Weather condition filter
 
436
  selected_weather = st.selectbox('Select Weather Condition:', weather)
437
 
438
  # Create and display line graph
439
+
440
+ trend_col, desc_col = st.columns([7, 3])
441
+
442
+ with trend_col:
443
+ st.markdown("### Crash Trend Over Time")
444
+ trend_fig = create_crash_trend_chart(df, selected_weather)
445
+ # Update the figure layout for larger size
446
+ trend_fig.update_layout(
447
+ height=800, # Increased height
448
+ width=None, # Let width be responsive
449
+ margin=dict(l=50, r=50, t=50, b=50)
450
+ )
451
+ st.plotly_chart(trend_fig, use_container_width=True)
452
+
453
+ with desc_col:
454
+ st.markdown("""
455
+ ## **Crash Trend Over Time**
456
+ This interactive line chart visualizes the trend of unique traffic crashes over the years, optionally filtered by weather conditions. It highlights how crash frequency changes over time, helping identify trends and potential contributing factors.
457
+ **Key Features:**
458
+ * **Time Trend Analysis**: Displays the total number of unique crashes for each year, showing long-term patterns.
459
+ * **Weather Filter**: Users can filter the data by weather conditions (e.g., "Rainy", "Sunny") to analyze how weather impacts crash trends.
460
+ * **Interactive Tooltips**: Hovering over data points reveals the exact crash count for each year, providing detailed insights.
461
+ **Color Scheme and Design:**
462
+ * **Line and Markers**: A smooth line connects data points, with prominent markers for each year to highlight trends clearly.
463
+ * **Dynamic Title**: The chart updates its title to reflect the selected weather condition or "All Conditions" for the overall trend.
464
+ **Insights:**
465
+ This chart helps uncover:
466
+ * Annual fluctuations in crash incidents.
467
+ * Correlations between weather conditions and crash frequencies.
468
+ * Historical patterns that can guide future safety measures and urban planning decisions
469
+ """)
470
+
471
 
472
  with tab4:
473
  # Dropdown for Unit Type selection
 
479
  unit_type_pairs = sorted(list(unit_type_pairs))
480
  unit_type = st.selectbox("Select Unit Type Pair", options=['Total'] + unit_type_pairs)
481
 
482
+ # # Create 5th Visualization: Injuries and fatalities chart
483
+ # injuries_fatalities_chart = create_injuries_fatalities_chart(df, unit_type)
484
+ # st.altair_chart(injuries_fatalities_chart, use_container_width=True)
485
+
486
+ # st.markdown("""
487
+ # This line chart shows the **total number of injuries and fatalities by month for the selected unit type pair**. The blue line represents total injuries, while the red line represents total fatalities. Observing the trends over the months can help identify any seasonal patterns or peaks in traffic incidents involving specific unit types.
488
+
489
+ # - **Total Injuries**: The blue line indicates how injuries vary over different months, highlighting any particular spikes or declines.
490
+ # - **Total Fatalities**: The red line shows the trend for fatalities, which is generally much lower compared to injuries.
491
+ # - **Unit Types**: The dropdown selection allows users to filter the data by specific unit type pairs (e.g., Driver vs Pedestrian) or view the overall trend across all types.
492
+
493
+ # This visualization aims to provide an intuitive understanding of how injuries and fatalities are distributed across the year, helping stakeholders develop targeted safety measures.
494
+ # """)
495
+
496
+ chart_col, desc_col = st.columns([7, 3])
497
+
498
+ with chart_col:
499
+ # Create 5th Visualization: Injuries and fatalities chart
500
+ injuries_fatalities_chart = create_injuries_fatalities_chart(df, unit_type)
501
+ injuries_fatalities_chart = injuries_fatalities_chart.properties(
502
+ height=800 # Make the chart taller to match the description column
503
+ )
504
+ st.altair_chart(injuries_fatalities_chart, use_container_width=True)
505
+
506
+ with desc_col:
507
+ st.markdown("""
508
+ ## Injuries and Fatalities Trends
509
+
510
+ This line chart shows the **total number of injuries and fatalities by month for the selected unit type pair**. The visualization helps identify seasonal patterns and critical trends in traffic incidents involving specific unit types.
511
+
512
+ **Key Features:**
513
+ * **Injuries Trend** (Blue Line)
514
+ - Tracks monthly injury counts
515
+ - Shows seasonal variations
516
+ - Identifies peak incident periods
517
+
518
+ * **Fatalities Trend** (Red Line)
519
+ - Monitors monthly fatality counts
520
+ - Generally lower than injuries
521
+ - Highlights critical safety concerns
522
+
523
+ * **Interactive Selection**
524
+ - Filter by specific unit type pairs
525
+ - Compare different vehicle combinations
526
+ - View overall trends across all types
527
+
528
+ **Applications:**
529
+ - Identify high-risk months
530
+ - Guide seasonal safety measures
531
+ - Inform emergency response planning
532
+ - Support targeted intervention strategies
533
+
534
+ This visualization aids stakeholders in developing effective safety measures and resource allocation strategies throughout the year.
535
+ """)
536
+
537
+
538
 
539
  with tab5:
540
  # Dropdown for category selection
 
552
  years = ['All Years'] + sorted(df['Year'].dropna().unique().astype(int).tolist())
553
  selected_year = st.selectbox("Select Year:", years)
554
 
555
+ chart_col, desc_col = st.columns([7, 3])
556
+
557
+ with chart_col:
558
+ st.markdown(f"### Distribution of Incidents by {selected_category}")
559
+ distribution_chart = create_category_distribution_chart(df, selected_category, selected_year)
560
+ # Update the figure layout for larger size
561
+ distribution_chart.update_layout(
562
+ height=800, # Increased height
563
+ width=None, # Let width be responsive
564
+ margin=dict(l=50, r=50, t=50, b=50)
565
+ )
566
+ st.plotly_chart(distribution_chart, use_container_width=True)
567
+
568
+ with desc_col:
569
+ st.markdown("""
570
+ ## Distribution by Category
571
+ This visualization explores the distribution of traffic incidents across various categories, such as Collision Manner, Weather, Surface Condition, Alcohol Use, and Driver Gender. Each bar represents a specific category value (e.g., "Male" or "Female" for Gender), and the bars are divided into segments based on Injury Severity (e.g., Minor, Moderate, Serious, Fatal).
572
+
573
+ **Key features include:**
574
+ * Interactive Filters: Select a category and filter by year to analyze trends over time.
575
+ * Insightful Tooltips: Hover over each segment to view the exact count and percentage of incidents for a given severity level.
576
+ * Comparative Analysis: Quickly identify how different conditions or behaviors correlate with injury severity.
577
+
578
+ This chart provides actionable insights into factors contributing to traffic incidents and their outcomes, helping stakeholders target interventions and improve road safety.
579
+ """)
580
 
581
 
582
  if __name__ == "__main__":