File size: 34,233 Bytes
2b51b88
 
 
 
aeb42a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b51b88
 
 
aeb42a6
 
2b51b88
aeb42a6
 
 
 
2b51b88
aeb42a6
 
 
2b51b88
aeb42a6
 
 
 
 
 
 
 
2b51b88
aeb42a6
 
 
 
 
 
 
 
 
 
 
 
2b51b88
aeb42a6
 
 
 
 
 
2b51b88
aeb42a6
2b51b88
aeb42a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b51b88
 
aeb42a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b51b88
aeb42a6
 
 
2b51b88
aeb42a6
 
 
2b51b88
aeb42a6
 
 
 
2b51b88
aeb42a6
 
 
 
 
 
 
2b51b88
 
 
aeb42a6
 
 
2b51b88
 
 
 
 
 
 
aeb42a6
 
 
 
 
2b51b88
 
 
 
 
 
aeb42a6
 
 
 
 
 
 
2b51b88
 
 
aeb42a6
 
 
 
 
 
 
 
 
 
 
 
2b51b88
aeb42a6
2b51b88
 
 
 
aeb42a6
2b51b88
 
 
 
aeb42a6
2b51b88
 
aeb42a6
 
 
 
 
 
 
2b51b88
 
aeb42a6
 
 
 
 
 
 
 
 
 
 
 
 
 
2b51b88
 
 
 
aeb42a6
 
 
2b51b88
 
 
aeb42a6
2b51b88
aeb42a6
2b51b88
 
 
aeb42a6
 
2b51b88
 
 
 
 
 
 
 
 
 
 
aeb42a6
 
 
 
 
 
 
2b51b88
 
aeb42a6
2b51b88
aeb42a6
 
 
 
 
 
 
 
 
2b51b88
aeb42a6
2b51b88
aeb42a6
 
 
 
 
 
 
 
 
 
 
 
 
 
2b51b88
 
aeb42a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b51b88
aeb42a6
2b51b88
aeb42a6
2b51b88
aeb42a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b51b88
aeb42a6
2b51b88
aeb42a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
import numpy as np
import pandas as pd
import altair as alt
import streamlit as st
import geopandas as gpd
import json

st.set_page_config(layout="wide")

st.markdown("""
    <style>
    select {
        font-size: 20px !important;
    }
    label {
        font-size: 20px !important;   
    }
    </style>
""", unsafe_allow_html=True)

@st.cache_data
def load_data():
    df1 = pd.read_csv("https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Traffic_Crashes_-_Crashes_20250420.csv")
    df1 = df1.dropna(subset=['LATITUDE', 'LONGITUDE'])

    # df2 = gpd.read_file('https://data.cityofchicago.org/resource/igwz-8jzy.geojson')
    df2 = gpd.read_file("https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Boundaries%20-%20Community%20Areas_20250504.geojson")
    
    return df1, df2

@st.cache_data
def preprocess_data():
    traffic, areas = load_data()

    traffic['CRASH_DATE'] = pd.to_datetime(traffic['CRASH_DATE'])
    traffic['YEAR'] = traffic['CRASH_DATE'].dt.year
    traffic = traffic[
        (traffic['YEAR'].between(2018, 2024)) &
        (traffic['INJURIES_TOTAL'] > 0) &
        (traffic['LONGITUDE'] != 0) & (traffic['LATITUDE'] != 0)
    ]
    traffic['DAY_TYPE'] = traffic['CRASH_DAY_OF_WEEK'].apply(lambda x: 'Weekend' if x in [1, 7] else 'Weekday')

    areas['geometry_area'] = areas.geometry
    traffic_gdf = gpd.GeoDataFrame(
        traffic,
        geometry=gpd.points_from_xy(traffic['LONGITUDE'], traffic['LATITUDE']),
        crs="EPSG:4326"
    )
    traffic_gdf2 = gpd.sjoin(
        traffic_gdf,
        areas[['area_numbe', 'community', 'geometry', 'geometry_area']],
        how='left',
        predicate='within'
    )

    polygon_unique = traffic_gdf2[['geometry_area', 'community', 'area_numbe', 'INJURIES_TOTAL', 'YEAR']].dropna().copy()
    polygon_unique = polygon_unique.groupby(['geometry_area', 'community', 'area_numbe', 'YEAR']).agg(
        INJURIES_TOTAL=('INJURIES_TOTAL', 'sum')
    ).reset_index()
    polygon_unique = polygon_unique.set_geometry('geometry_area')
    geojson_data = json.loads(polygon_unique.to_json())

    return traffic_gdf2, geojson_data

st.title("🚦 Injured on the Way: An Overview of Chicago Traffic Injuries (2018-2024)")

# today = datetime.today().strftime("%B %d, %Y") 
st.markdown(
    f"<span style='font-size:18px; color:black;'>By Keyu (Chloe) Cai, Yutong Zheng | Updated May 05, 2025</span>",
    unsafe_allow_html=True
)

st.markdown("---")
st.subheader('Understand the Traffic Crash Data in City of Chicago with Us:')

# st.title('Streamlit App for IS445 FP3')
# st.subheader('Created by Keyu (Chloe) Cai and Yutong Zheng')
# # st.text('Created by Keyu (Chloe) Cai and Yutong Zheng (Group 8)')
# st.header('Dashboard for Interactive Visualization')

st.markdown("""
<div style='font-size:20px; line-height:1.6; text-align: justify;'>
Traffic safety is a concern for every city, and Chicago is no exception. 
Every year, more than 100,000 crashes occur on its streets, many of which result in injuries or even fatalities. 
Understanding the patterns behind these incidents—when they happen, where they happen, and under what conditions—is essential for making informed decisions about infrastructure, traffic enforcement, and public awareness.
We take a closer look at traffic injury data from Chicago between 2018 and 2024 to uncover trends that might help reduce future accidents. 
By turning raw data into clear visualizations, we hope to make these insights more accessible and useful for anyone who cares about safer roads.
</div>
""", unsafe_allow_html=True)

st.markdown('---')

st.markdown("""
    <div style='font-size:22px; font-weight:bold; margin-bottom:10px;'>🚦 Where Injuries Happen Most in Chicago</div>
    <div style='font-size:20px; line-height:1.6; text-align: justify;'>
    The map (top-left heatmap) shows that traffic-related injuries are not evenly distributed across Chicago. From 2018 to 2024, areas like Austin (Community Area 25), Near North Side (8), Near West Side (28), and Greater Grand Crossing (69) have consistently seen higher numbers of injuries. 
    These neighborhoods vary widely in terms of population, economic background, and city infrastructure. For example, some are crowded with residents or located near downtown with busy roads and heavy traffic, while others may face infrastructure challenges or limited traffic safety resources. 
    At the same time, many other parts of the city show lower levels of injuries, especially in areas with fewer major intersections or lower vehicle and pedestrian volume. Overall, this pattern suggests that both urban activity and resource allocation may influence where and how often injuries happen on Chicago’s roads.
    </div>
""", unsafe_allow_html=True)

st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)

st.markdown(
    """
    <div style='font-size:22px; font-weight:bold; margin-bottom:10px;'>🚦 Hourly Crash Patterns: Weekdays vs Weekends</div>
    <div style='font-size:20px; line-height:1.6; text-align: justify;'>
    When looking at citywide data from 2018 to 2024, we see a clear pattern in when crashes with injuries tend to happen (see top-right line chart). 
    During the early morning to early evening hours (roughly 6 AM to 8 PM), weekdays consistently see more crashes per hour than weekends. This likely reflects heavier traffic during commute times, school drop-offs, and busy weekday routines. 
    In contrast, during late-night and very early morning hours, weekends tend to have more crashes, possibly tied to nightlife or late travel. 
    While this pattern is clear accross the whole city, it’s important to note that  different community areas may show their unique trends based on their local traffic, population, and neighborhood activity.
    </div>
    """,
    unsafe_allow_html=True
)

st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)

st.markdown(
    """
    <div style='font-size:22px; font-weight:bold; margin-bottom:10px;'>🚦 Fatal Injuries Are More Common in Darker Lighting Conditions</div>
    <div style='font-size:20px; line-height:1.6; text-align: justify;'>
    Between 2018 and 2024, crash data shows that deadly injuries are more likely to happen and fatal injury rates are generally higher in darker conditions (see bottom-left bar chart). 
    The colors are assigned based on lighting brightness — the darker the lighting condition, the deeper the blue color shade.
    The three most dangerous lighting conditions with the highest fatal injury rates are usually <b>“Darkness, Lighted Road,” “Darkness,”</b> and <b>“Dusk.”</b> 
    Although their exact ranking changes a bit each year, these three consistently lead, highlighting that poor lighting can be risky even when streetlights are present. 
    On the other hand, conditions like <b>“Daylight”</b> and <b>“Dawn”</b> tend to have lower fatal injury rates. 
    These findings align with common traffic safety concerns—drivers may have longer reaction times or reduced awareness in low-light settings. 
    </div>
    """,
    unsafe_allow_html=True
)

st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)

st.markdown(
    """
    <div style='font-size:22px; font-weight:bold; margin-bottom:10px;'>🚦 Crash Damage Levels Over the Years</div>
    <div style='font-size:20px; line-height:1.6; text-align: justify;'>
    From 2018 to 2024, crashes that caused <b>over $1,500 in damage</b> have consistently made up the largest portion of all injury-related crashes in Chicago (see bottom-right grouped bar chart). 
    While the overall number of such cases dropped slightly in 2020—possibly due to reduced traffic during the pandemic—but then numbers quickly rose again in the following years and even reached new highs in 2024. 
    In comparison, crashes with less cost (under $1,500) have remained relatively stable or even decreased slightly over time.
    This trend could suggest more serious crashes happening or better reporting of higher-cost accidents. 
    It’s also worth noting that while this is the overall city trend, when we look at different community areas, some show steadier numbers while others have more fluctuation in damage levels. 
    Factors like road design, local driving behavior, and traffic volume may all play a role.
    </div>
    """,
    unsafe_allow_html=True
)

st.markdown('---')

st.subheader('Explore More Through Our Interactive Dashboard!')
st.markdown("<span style='font-size:18px; color:gray;'>" \
"Use the dropdown in the bottom-left to select a different year. " \
"You can also click on different areas in the heatmap to update the other charts based on that specific community.</span>", 
unsafe_allow_html=True)

# st.markdown("<p style='color:gray; font-size:16px;'>Scroll down to explore trends in injury-related crashes by time, location, lighting condition, and damage level.</p>", unsafe_allow_html=True)

# traffic, areas = load_data()

# # Transform date column
# traffic['CRASH_DATE'] = pd.to_datetime(traffic['CRASH_DATE'])

# # Raw dataset already has 'Hour' and 'Month'
# traffic['YEAR'] = traffic['CRASH_DATE'].dt.year
# traffic['DY']   = traffic['CRASH_DATE'].dt.day

# traffic_analysis = traffic.loc[:, traffic.columns.isin(['YEAR', 'LONGITUDE', 'LATITUDE', 'CRASH_DAY_OF_WEEK',
#                                                         'INJURIES_TOTAL', 'CRASH_HOUR', 'LIGHTING_CONDITION',
#                                                         'DAMAGE','INJURIES_FATAL'])]
# # Select years with complete records (2018-2024)
# traffic_analysis = traffic_analysis[(traffic_analysis['YEAR'].isin(range(2018, 2025))) & (traffic_analysis['INJURIES_TOTAL'] > 0)].copy()
# traffic_analysis = traffic_analysis[(traffic_analysis['LONGITUDE'] != 0) & (traffic_analysis['LATITUDE'] != 0)].copy()

# # Add Weekday/Weekend label for each record
# traffic_analysis['DAY_TYPE'] = traffic_analysis['CRASH_DAY_OF_WEEK'].apply(lambda x: 'Weekend' if x in [1, 7] else 'Weekday')

# # Prepare for plotting community areas
# areas['geometry_area'] = areas.geometry
# traffic_gdf = gpd.GeoDataFrame(
#     traffic_analysis,
#     geometry=gpd.points_from_xy(traffic_analysis['LONGITUDE'], traffic_analysis['LATITUDE']),
#     crs="EPSG:4326"
# )

# traffic_gdf2 = gpd.sjoin(traffic_gdf, areas[['area_numbe', 'community', 'geometry', 'geometry_area']], how='left', predicate='within')
# # Deduplicate
# polygon_unique = traffic_gdf2[['geometry_area', 'community', 'area_numbe', 'INJURIES_TOTAL', 'YEAR']].dropna().copy()

# # Aggregation
# polygon_unique = polygon_unique.groupby(['geometry_area', 'community', 'area_numbe', 'YEAR']
#                                         ).agg(INJURIES_TOTAL=('INJURIES_TOTAL', 'sum')).reset_index()

# polygon_unique = polygon_unique.set_geometry('geometry_area')
# geojson_data = json.loads(polygon_unique.to_json())

traffic_gdf2, geojson_data = preprocess_data()

alt.data_transformers.disable_max_rows()
selection = alt.selection_point(fields=["area_numbe"])
 
year_selector = alt.selection_single(
    fields=["YEAR"],
    bind=alt.binding_select(
        options=sorted(traffic_gdf2['YEAR'].unique()),
        name='Select Year: '
    )
)

# selected_year = st.selectbox("Select Year: ", sorted(traffic_gdf2["YEAR"].unique()))

# filtered_features = [
#     f for f in geojson_data["features"]
#     if f["properties"]["YEAR"] == selected_year
# ]

# filtered_geojson = {"type": "FeatureCollection", "features": filtered_features}

# Driver plot: Heatmap of Injuries Total by Location in City of Chicago
# chart = alt.Chart(alt.Data(values=geojson_data['features'])).mark_geoshape(stroke='white', strokeWidth=0.8).encode(
chart = alt.Chart(alt.Data(values=geojson_data["features"])).mark_geoshape(stroke='white', strokeWidth=0.8).encode(
    color=alt.condition(
        selection,
        alt.Color('properties.INJURIES_TOTAL:Q',
                    scale=alt.Scale(scheme='yellowgreenblue'),
                    legend=alt.Legend(orient='left', title='Total Injuries', offset=20, titlePadding=15)),
        alt.value('lightgray')
    ),
    tooltip=[
    alt.Tooltip('properties.area_numbe:N', title='Area Number'),
    alt.Tooltip('properties.community:N', title='Community Name'),
    alt.Tooltip('properties.INJURIES_TOTAL:Q', title='Total Injuries')
    ]
).transform_calculate(
    area_numbe='datum.properties.area_numbe',
    YEAR='datum.properties.YEAR'
).add_params(
    selection,
    year_selector
).transform_filter(
    year_selector
).properties(
    width=350,
    height=350,
    # title='Heatmap of Injuries Total by Location in City of Chicago',
    title=alt.TitleParams(
    text='Heatmap of Total Injuries by Location in City of Chicago',
    anchor='middle'
    )
)

# Driven plot 1: Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend
line = alt.Chart(traffic_gdf2.drop(columns=['geometry_area'])).transform_filter(
    selection,
    year_selector
).transform_aggregate(
    crash_count='count()',
    groupby=['CRASH_HOUR', 'DAY_TYPE'] 
).transform_calculate(
    adjusted_count="datum.DAY_TYPE == 'Weekday' ? datum.crash_count / 5 : datum.crash_count / 2" 
).mark_line(point=True).encode(
    x=alt.X('CRASH_HOUR:O', title='Hour of Day'),
    y=alt.Y('adjusted_count:Q', title='Average Number of Injury-Related Crashes', axis=alt.Axis(grid=False)),
    color=alt.Color('DAY_TYPE:N', scale=alt.Scale(
        domain=['Weekday', 'Weekend'],
        range=['#225ea8', '#c7e9b4']
    ), legend=alt.Legend(title='Day Type', titlePadding=15)),
    tooltip=[
        alt.Tooltip('CRASH_HOUR:O', title='Hour of Day'),
        alt.Tooltip('DAY_TYPE:N', title='Day Type'),
        alt.Tooltip('adjusted_count:Q', title='Average Count', format=',d')
    ]
).properties(
    width=350,
    height=350,
    # title='Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend',
    title=alt.TitleParams(
        text='Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend',
        anchor='middle'
    )
)

# Driven plot 2: Fatal Injury Rate of Different Lighting Conditions
bar1 = alt.Chart(traffic_gdf2.drop(columns=['geometry_area'])).transform_filter(
    selection,
    year_selector
).transform_calculate(
    is_fatal="datum.INJURIES_FATAL > 0 ? 1 : 0"
).transform_aggregate(
    total='count()',
    fatal='sum(is_fatal)',
    groupby=['LIGHTING_CONDITION']
).transform_calculate(
    fatal_rate='datum.fatal / datum.total'
).mark_bar().encode(
    x=alt.X('LIGHTING_CONDITION:N', sort='-y', title='Lighting Condition'),
    y=alt.Y('fatal_rate:Q', axis=alt.Axis(format='%', grid=False), title='Fatal Injury Rate'),
    color=alt.Color('LIGHTING_CONDITION:N', 
                    scale=alt.Scale(
                        domain=['DARKNESS', 'DARKNESS, LIGHTED ROAD', 'DAWN', 'DUSK', 'DAYLIGHT', 'UNKNOWN'],
                        range=['#084C88', '#2A6FB6', '#4FA3D9', '#7EC8E3', '#BFEFFF', '#E0F7FA']
                        # range=['#253494', '#225ea8', '#1d91c0', '#41b6c4', '#7fcdbb', '#c7e9b4', '#edf8b1']
                    ),
                    legend=alt.Legend(orient='left', title='Lighting Condition', titlePadding=15)),
    tooltip=[
        alt.Tooltip('LIGHTING_CONDITION:N', title='Lighting Condition'),
        alt.Tooltip('fatal_rate:Q', title='Fatal Injury Rate', format='.2%')
    ]
).properties(
    width=400,
    height=350,
    # title='Fatal Injury Rate of Different Lighting Conditions',
    title=alt.TitleParams(
        text='Fatal Injury Rate of Different Lighting Conditions',
        anchor='middle'
    )
)

# Driven plot 2: Fatal Injury Rate of Different Lighting Conditions
# bar1 = alt.Chart(traffic_gdf2.drop(columns=['geometry_area'])).mark_bar().encode(
#     x=alt.X('LIGHTING_CONDITION:N', sort='-y', title='Lighting Condition'),
#     y=alt.Y('mean(INJURIES_FATAL):Q', scale=alt.Scale(domainMin=0), axis=alt.Axis(format='%'), title='Fatal Injury Rate'),
#     color=alt.Color('LIGHTING_CONDITION:N', 
#                     scale=alt.Scale(
#                         domain=['DARKNESS', 'DARKNESS, LIGHTED ROAD', 'DAWN', 'DUSK', 'DAYLIGHT', 'UNKNOWN'],
#                         range=['#084C88', '#2A6FB6', '#4FA3D9', '#7EC8E3', '#BFEFFF', '#E0F7FA']
#                     ),
#                     legend=alt.Legend(orient='left', title='Lighting Condition', titlePadding=15)),
#     tooltip=[
#         alt.Tooltip('LIGHTING_CONDITION:N', title='Lighting Condition'),
#         alt.Tooltip('mean(INJURIES_FATAL):Q', title='Fatal Injury Rate', format='.2f')
#     ]
# ).transform_filter(
#     selection
# ).properties(
#     width=400,
#     height=350,
#     title='Fatal Injury Rate of Different Lighting Conditions',
#     anchor='middle'
# )

# Driven plot 3: Trends in Crash Damage Costs by Year (2018–2024)
grouped_bar = alt.Chart(traffic_gdf2.drop(columns=['geometry_area'])).mark_bar().encode(
    x=alt.X('YEAR:O', title='Year'),
    y=alt.Y('count()', title='Count of Injury-Related Crashes', axis=alt.Axis(grid=False)),
    color=alt.Color('DAMAGE:N', 
                    scale=alt.Scale(
                    domain=['$500 OR LESS', '$501 - $1,500', 'OVER $1,500'],
                    # range=['#AEDFF7', '#4FA3D9', '#084C88']
                    range=['#c7e9b4', '#0e8fc3', '#084C88']
                    ),
                    title='Damage Level', legend=alt.Legend(title='Damage Level', titlePadding=15)),
    xOffset='DAMAGE:N',
    tooltip=[
        alt.Tooltip('YEAR:O', title='Year'),
        alt.Tooltip('DAMAGE:N', title='Damage Level'),
        alt.Tooltip('count()', title='Count')
    ]
).transform_filter(
    selection
).properties(
    width=450,
    height=350,
    # title='Annual Distribution of Crash Damage Levels (2018–2024)',
    title=alt.TitleParams(
        text='Annual Distribution of Crash Damage Levels (2018–2024)',
        anchor='middle'
    )
)

top_row = (chart|line)
bottom_row = (bar1|grouped_bar).resolve_scale(color='independent')
final_chart = (top_row & bottom_row).configure_axis(
                                        labelFontSize=16,
                                        titleFontSize=20
                                    ).configure_title(
                                        fontSize=24
                                    ).configure_legend(
                                        labelFontSize=16,
                                        titleFontSize=18
                                    )

st.altair_chart(final_chart, use_container_width=False)

# st.markdown('''
#             ### Dashboard Overview and Guidance
#             This dashboard presents an analysis based on the City of Chicago's injury-related crash data from 2018 to 2024. The original dataset (https://data.cityofchicago.org/Transportation/Traffic-Crashes-Crashes/85ca-t3if/data_preview) includes detailed information about crashes that resulted in injuries within the city during this time period.  
            
#             The top-left figure displays a colored map (heatmap) showing the geographic distribution of total injuries from crashes, with darker areas indicating places where more people were injured. This heatmap serves as the driver plot of the dashboard. Users can click and drag to select a specific region of interest, and the three driven plots will automatically update to reflect data from the selected area.  
            
#             The first driven plot (top right) shows the distribution of injury-related crashes across 24 hours, comparing patterns between weekdays and weekends. This chart reflects the number of crashes that caused injuries (not the total number of injuries like in the heatmap).   
            
#             The second driven plot (bottom left) illustrates how different lighting conditions (such as daylight, dusk, or darkness) are associated with variations in fatal injury rates. The lighting conditions are sorted from highest to lowest fatal injury rate.  
            
#             The third driven plot (bottom right) depicts the trend of crash counts across different damage cost levels from 2018 to 2024. The bar heights represent the number of crashes falling into each damage category for each year.
            
#             Overall, this dashboard highlights key insights from the crash dataset in terms of time, environment, and damage severity. It is designed to help anyone interested in traffic crash data better understand the dataset, and it may also offer valuable guidance for city planners or traffic management officials seeking to improve road safety.
#             ''')


st.markdown('---')

st.subheader('Contextual Visualization from Other Sources')

st.image('https://miro.medium.com/v2/resize:fit:640/format:webp/1*2wHu-JlqN-KHQ9mvzlog9Q.png', 
        caption='Viz 1: Density of Injured and Killed per Borough, by Area in New York City, 2013-2019', 
        width = 500)
st.image('https://www.researchgate.net/profile/Onur-Sevli/publication/363958427/figure/fig1/AS:11431281087201775@1664467072927/The-number-of-Fatal-Serious-and-Other-injuries-by-year-Data-from-San-Antonio-city-is.png',
        caption='Viz 2: Fatal/Serious vs Other Injuries in San Antonio City, 2011-2021',
        width = 600)
st.image('Viz3.png',
         caption='Viz 3: Traffic Fatalities, by Rural/Urban Classification, 2013-2022 (United States)',
        width = 600)
st.image('Viz4.png',
         caption='Viz 4: Fatality Rates per 100 Million VMT, by State, 2022',
        width = 600)

st.markdown('---')

st.subheader('Check out the Raw Data and Related Sources If Interested:')

st.markdown("""
<div style='font-size:22px; margin-top:15px; font-weight:bold;'>Datasets are hosted on HuggingFace for our application:</div>

<div style='font-size:20px;'>
<ul>
<li>
<b>Data 1:</b> 
<a href="https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Traffic_Crashes_-_Crashes_20250420.csv" target="_blank">https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Traffic_Crashes_-_Crashes_20250420.csv</a>
</li>

<li>
<b>Data 2:</b> 
<a href="https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Boundaries%20-%20Community%20Areas_20250504.geojson" target="_blank">https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Boundaries%20-%20Community%20Areas_20250504.geojson</a>
</li>
</ul>
</div>
""", unsafe_allow_html=True)

# st.markdown('''
#             Citations:
            
#             Viz 1: https://joycegemcanete.medium.com/simple-analysis-of-the-new-york-motor-vehicle-collision-dataset-c6f883646560 ,
            
#             Viz 2: Çelik, A., & Sevli, O. (2022). Predicting traffic accident severity using machine learning techniques. Turkish Journal of Forensic Sciences, 11(2), 79–83. https://doi.org/10.46810/tdfd.1136432
            
#             Viz 3: National Highway Traffic Safety Administration. (2024, June). *Overview of motor vehicle traffic crashes in 2022* (Report No. DOT HS 813 560). U.S. Department of Transportation.  
# [Link to original publication](https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813560)
#             ''')

st.markdown("""
<div style='font-size:22px; margin-top:15px; font-weight:bold;'>Citations:</div>

<div style='font-size:20px;'>
<ul>
<li>
<b>Viz 1:</b> Canete, J. G. (2023, June 8). <i>Simple analysis of the New York motor vehicle collision dataset</i>. Medium. 
<a href="https://joycegemcanete.medium.com/simple-analysis-of-the-new-york-motor-vehicle-collision-dataset-c6f883646560" target="_blank">https://joycegemcanete.medium.com/simple-analysis-of-the-new-york-motor-vehicle-collision-dataset-c6f883646560</a>
</li>

<li>
<b>Viz 2:</b> Çelik, A., & Sevli, O. (2022). <i>Predicting traffic accident severity using machine learning techniques.</i> Turkish Journal of Forensic Sciences, 11(2), 79–83. 
<a href="https://doi.org/10.46810/tdfd.1136432" target="_blank">https://doi.org/10.46810/tdfd.1136432</a>
</li>

<li>
<b>Viz 3:</b> National Highway Traffic Safety Administration. (2024, June). <i>Overview of motor vehicle traffic crashes in 2022</i> (Report No. DOT HS 813 560). U.S. Department of Transportation. 
<a href="https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813560" target="_blank">https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813560</a>
</li>

<li>
<b>Viz 4:</b> National Highway Traffic Safety Administration. (2024, September). <i>Summary of motor vehicle traffic crashes: 2022 data</i> (Report No. DOT HS 813 643). U.S. Department of Transportation.
<a href="https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813643" target="_blank">https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813643</a>
</li>

<li>
<b>Data 1:</b> City of Chicago. (n.d.). <i>Traffic Crashes - Crashes. </i> Chicago Data Portal. Retrieved April 20, 2025, from
<a href="https://data.cityofchicago.org/Transportation/Traffic-Crashes-Crashes/85ca-t3if" target="_blank">https://data.cityofchicago.org/Transportation/Traffic-Crashes-Crashes/85ca-t3if</a>
</li>

<li>
<b>Data 2:</b> City of Chicago. (n.d.). <i>Boundaries - Community Areas. </i> Chicago Data Portal. Retrieved May 4, 2025, from
<a href="https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Community-Areas/igwz-8jzy" target="_blank">https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Community-Areas/igwz-8jzy</a>
</li>
</ul>
</div>
""", unsafe_allow_html=True)

# # Driver plot: Heatmap of Injuries Total by Location in City of Chicago
# alt.data_transformers.disable_max_rows()
# selection = alt.selection_interval(encodings=['x','y'])
# chart = alt.Chart(traffic_analysis).mark_rect().encode(
#     x=alt.X('LONGITUDE:Q', bin=alt.Bin(maxbins=20), title='Longitude (°)'),
#     y=alt.Y('LATITUDE:Q', bin=alt.Bin(maxbins=20), title='Latitude (°)'),
#     color=alt.Color('sum(INJURIES_TOTAL):Q', 
#                     scale=alt.Scale(scheme='blues'), 
#                     title='Injuries Total',
#                     legend=alt.Legend(orient='left', offset=20, titlePadding=15)),
#     tooltip=[
#         alt.Tooltip('count()', title='Crash Count'),
#         alt.Tooltip('sum(INJURIES_TOTAL):Q', title='Injuries Total'),
#         alt.Tooltip('LATITUDE:Q', bin=True, title='Latitude bin'),
#         alt.Tooltip('LONGITUDE:Q', bin=True, title='Longitude bin')
#     ]
# ).add_params(
#     selection
# ).properties(
#     width=300,
#     height=300,
#     title='Heatmap of Injuries Total by Location in City of Chicago'
#     title=alt.TitleParams(
#     text='Heatmap of Injuries Total by Location in City of Chicago',
#     anchor='middle'  # <<< 关键在这里,anchor设成'middle'就是居中!
# )
# )

# # Driven plot 1: Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend
# line = alt.Chart(traffic_analysis).transform_filter(
#     selection
# ).transform_aggregate(
#     crash_count='count()',
#     groupby=['CRASH_HOUR', 'DAY_TYPE'] 
# ).transform_calculate(
#     adjusted_count="datum.DAY_TYPE == 'Weekday' ? datum.crash_count / 5 : datum.crash_count / 2" 
# ).mark_line(point=True).encode(
#     x=alt.X('CRASH_HOUR:O', title='Hour of Day'),
#     y=alt.Y('adjusted_count:Q', title='Average Number of Injury-Related Crashes'),
#     color=alt.Color('DAY_TYPE:N', legend=alt.Legend(title='Day Type', titlePadding=15)),
#     tooltip=[
#         alt.Tooltip('CRASH_HOUR:O', title='Hour of Day'),
#         alt.Tooltip('DAY_TYPE:N', title='Day Type'),
#         alt.Tooltip('adjusted_count:Q', title='Average Count', format=',d')
#     ]
# ).properties(
#     width=300,
#     height=300,
#     title='Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend'
# )

# # line = alt.Chart(traffic_analysis).mark_line(point=True).encode(
# #     x=alt.X('CRASH_HOUR:O', title='Hour of Day'),
# #     y=alt.Y('count()', title='Number of Injury-Related Crashes'),
# #     color=alt.Color('DAY_TYPE:N', legend=alt.Legend(title='Day Type'))
# # ).transform_filter(
# #     selection
# # ).properties(
# #     width=300,
# #     height=300,
# #     title='Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend'
# # )


# # Driven plot 2: Fatal Injury Rate of Different Lighting Conditions
# bar1 = alt.Chart(traffic_analysis).mark_bar().encode(
#     x=alt.X('LIGHTING_CONDITION:N', sort='-y', title='Lighting Condition'),
#     y=alt.Y('mean(INJURIES_FATAL):Q', scale=alt.Scale(domainMin=0), axis=alt.Axis(format='%'), title='Fatal Injury Rate'),
#     color=alt.Color('LIGHTING_CONDITION:N', 
#                     scale=alt.Scale(
#                         domain=['DARKNESS', 'DARKNESS, LIGHTED ROAD', 'DAWN', 'DUSK', 'DAYLIGHT', 'UNKNOWN'],
#                         range=['#084C88', '#2A6FB6', '#4FA3D9', '#7EC8E3', '#BFEFFF', '#E0F7FA']
#                     ),
#                     legend=alt.Legend(orient='left', title='Lighting Condition', titlePadding=15)),
#     tooltip=[
#         alt.Tooltip('LIGHTING_CONDITION:N', title='Lighting Condition'),
#         alt.Tooltip('mean(INJURIES_FATAL):Q', title='Fatal Injury Rate', format='.2f')
#     ]
# ).transform_filter(
#     selection
# ).properties(
#     width=300,
#     height=300,
#     title='Fatal Injury Rate of Different Lighting Conditions'
# )


# # bar2 = alt.Chart(traffic_analysis).mark_bar().encode(
# #     x=alt.X('WEATHER_CONDITION:N'),
# #     y=alt.Y('mean(INJURIES_FATAL):Q'),
# #     color=alt.Color('WEATHER_CONDITION:N', 
# #                     legend=alt.Legend(orient='right'))
# # ).transform_filter(
# #     selection
# # ).properties(
# #     width=400,
# #     height=400
# # )

# # Driven plot 3: Trends in Crash Damage Costs by Year (2018–2024)
# grouped_bar = alt.Chart(traffic_analysis).mark_bar().encode(
#     x=alt.X('YEAR:O', title='Year'),
#     y=alt.Y('count()', title='Count'),
#     color=alt.Color('DAMAGE:N', 
#                     scale=alt.Scale(
#                     domain=['$500 OR LESS', '$501 - $1,500', 'OVER $1,500'],
#                     range=['#AEDFF7', '#4FA3D9', '#084C88']
#                     ),
#                     title='Damage Level', legend=alt.Legend(title='Damage Level', titlePadding=15)),
#     xOffset='DAMAGE:N',
#     tooltip=[
#         alt.Tooltip('YEAR:O', title='Year'),
#         alt.Tooltip('DAMAGE:N', title='Damage Level'),
#         alt.Tooltip('count()', title='Count')
#     ]
# ).transform_filter(
#     selection
# ).properties(
#     width=300,
#     height=300,
#     title='Annual Distribution of Crash Damage Levels (2018–2024)'
# )

# top_row = chart|line
# bottom_row = (bar1|grouped_bar).resolve_scale(color='independent')
# final_chart = top_row & bottom_row

# # top_row = alt.hconcat(chart, line).resolve_scale(color='independent')
# # bottom_row = alt.hconcat(bar1, grouped_bar).resolve_scale(color='independent')

# # final_chart = alt.vconcat(top_row, bottom_row)

# st.altair_chart(final_chart, use_container_width=False)

# st.markdown('''
#             ### Dashboard Overview and Guidance
#             This dashboard presents an analysis based on the City of Chicago's injury-related crash data from 2018 to 2024. The original dataset (https://data.cityofchicago.org/Transportation/Traffic-Crashes-Crashes/85ca-t3if/data_preview) includes detailed information about crashes that resulted in injuries within the city during this time period.  
            
#             The top-left figure displays a colored map (heatmap) showing the geographic distribution of total injuries from crashes, with darker areas indicating places where more people were injured. This heatmap serves as the driver plot of the dashboard. Users can click and drag to select a specific region of interest, and the three driven plots will automatically update to reflect data from the selected area.  
            
#             The first driven plot (top right) shows the distribution of injury-related crashes across 24 hours, comparing patterns between weekdays and weekends. This chart reflects the number of crashes that caused injuries (not the total number of injuries like in the heatmap).   
            
#             The second driven plot (bottom left) illustrates how different lighting conditions (such as daylight, dusk, or darkness) are associated with variations in fatal injury rates. The lighting conditions are sorted from highest to lowest fatal injury rate.  
            
#             The third driven plot (bottom right) depicts the trend of crash counts across different damage cost levels from 2018 to 2024. The bar heights represent the number of crashes falling into each damage category for each year.
            
#             Overall, this dashboard highlights key insights from the crash dataset in terms of time, environment, and damage severity. It is designed to help anyone interested in traffic crash data better understand the dataset, and it may also offer valuable guidance for city planners or traffic management officials seeking to improve road safety.
#             ''')

# st.markdown('''
#     #### Contexual Dataset
#     We have found a contextual dataset, which can be accessed at https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Community-Areas/igwz-8jzy. This dataset shows the boundaries of the 77 community areas in Chicago. Adding this dataset to our project will help us group traffic accidents by these areas instead of just using latitude and longitude. This makes it easier for people to understand where accidents happen more often and helps tell a clearer story about which neighborhoods have more traffic safety issues.
# ''')

# st.markdown('''
#             #### Hosting Datasets
#             We would continue our plan for hosting original dataset on HuggingFace like Part 1 (https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Traffic_Crashes_-_Crashes_20250420.csv). To ensure consistency across all datasets, we also decided to host the contextual dataset on Hugging Face as well (https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Boundaries_-_Community_Areas_20250424.csv).
#             ''')