Chloecky commited on
Commit
aeb42a6
·
verified ·
1 Parent(s): 2f7a5b5

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +563 -109
app.py CHANGED
@@ -2,70 +2,260 @@ import numpy as np
2
  import pandas as pd
3
  import altair as alt
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  @st.cache_data
7
  def load_data():
8
- df = pd.read_csv("https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Traffic_Crashes_-_Crashes_20250420.csv")
9
- df = df.dropna(subset=['LATITUDE', 'LONGITUDE'])
10
- return df
11
 
12
- st.set_page_config(layout="wide")
 
 
 
13
 
14
- st.title('Streamlit App for IS445 FP2')
15
- st.text('Group 8: Keyu (Chloe) Cai, Yutong Zheng')
 
16
 
17
- traffic = load_data()
 
 
 
 
 
 
 
18
 
19
- # Transform date column
20
- traffic['CRASH_DATE'] = pd.to_datetime(traffic['CRASH_DATE'])
 
 
 
 
 
 
 
 
 
 
21
 
22
- # Raw dataset already has 'Hour' and 'Month'
23
- traffic['YEAR'] = traffic['CRASH_DATE'].dt.year
24
- traffic['DY'] = traffic['CRASH_DATE'].dt.day
 
 
 
25
 
26
- traffic_analysis = traffic.loc[:, ~traffic.columns.isin(['CRASH_RECORD_ID', 'CRASH_DATE_EST_I',
27
- 'REPORT_TYPE', 'INTERSECTION_RELATED_I', 'NOT_RIGHT_OF_WAY_I',
28
- 'HIT_AND_RUN_I', 'PHOTOS_TAKEN_I', 'STATEMENTS_TAKEN_I',
29
- 'DOORING_I', 'WORK_ZONE_I', 'WORK_ZONE_TYPE', 'WORKERS_PRESENT_I',
30
- 'LOCATION'])]
31
- # Select years with complete records
32
- traffic_analysis = traffic_analysis[(traffic_analysis['YEAR'].isin(range(2018, 2025))) & (traffic_analysis['INJURIES_TOTAL'] > 0)].copy()
33
- traffic_analysis = traffic_analysis[(traffic_analysis['LONGITUDE'] != 0) & (traffic_analysis['LATITUDE'] != 0)].copy()
34
 
35
- # Add Weekday/Weekend label for each record
36
- traffic_analysis['DAY_TYPE'] = traffic_analysis['CRASH_DAY_OF_WEEK'].apply(lambda x: 'Weekend' if x in [1, 7] else 'Weekday')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- # Driver plot: Heatmap of Injuries Total by Location in City of Chicago
39
  alt.data_transformers.disable_max_rows()
40
- selection = alt.selection_interval(encodings=['x','y'])
41
- chart = alt.Chart(traffic_analysis).mark_rect().encode(
42
- x=alt.X('LONGITUDE:Q', bin=alt.Bin(maxbins=20), title='Longitude (°)'),
43
- y=alt.Y('LATITUDE:Q', bin=alt.Bin(maxbins=20), title='Latitude (°)'),
44
- color=alt.Color('sum(INJURIES_TOTAL):Q',
45
- scale=alt.Scale(scheme='blues'),
46
- title='Injuries Total',
47
- legend=alt.Legend(orient='left', offset=20, titlePadding=15)),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  tooltip=[
49
- alt.Tooltip('count()', title='Crash Count'),
50
- alt.Tooltip('sum(INJURIES_TOTAL):Q', title='Injuries Total'),
51
- alt.Tooltip('LATITUDE:Q', bin=True, title='Latitude bin'),
52
- alt.Tooltip('LONGITUDE:Q', bin=True, title='Longitude bin')
53
  ]
 
 
 
54
  ).add_params(
55
- selection
 
 
 
56
  ).properties(
57
- width=300,
58
- height=300,
59
- title='Heatmap of Injuries Total by Location in City of Chicago'
60
- # title=alt.TitleParams(
61
- # text='Heatmap of Injuries Total by Location in City of Chicago',
62
- # anchor='middle' # <<< 关键在这里,anchor设成'middle'就是居中!
63
- # )
64
  )
65
 
66
  # Driven plot 1: Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend
67
- line = alt.Chart(traffic_analysis).transform_filter(
68
- selection
 
69
  ).transform_aggregate(
70
  crash_count='count()',
71
  groupby=['CRASH_HOUR', 'DAY_TYPE']
@@ -73,75 +263,94 @@ line = alt.Chart(traffic_analysis).transform_filter(
73
  adjusted_count="datum.DAY_TYPE == 'Weekday' ? datum.crash_count / 5 : datum.crash_count / 2"
74
  ).mark_line(point=True).encode(
75
  x=alt.X('CRASH_HOUR:O', title='Hour of Day'),
76
- y=alt.Y('adjusted_count:Q', title='Average Number of Injury-Related Crashes'),
77
- color=alt.Color('DAY_TYPE:N', legend=alt.Legend(title='Day Type', titlePadding=15)),
 
 
 
78
  tooltip=[
79
  alt.Tooltip('CRASH_HOUR:O', title='Hour of Day'),
80
  alt.Tooltip('DAY_TYPE:N', title='Day Type'),
81
  alt.Tooltip('adjusted_count:Q', title='Average Count', format=',d')
82
  ]
83
  ).properties(
84
- width=300,
85
- height=300,
86
- title='Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend'
 
 
 
 
87
  )
88
 
89
- # line = alt.Chart(traffic_analysis).mark_line(point=True).encode(
90
- # x=alt.X('CRASH_HOUR:O', title='Hour of Day'),
91
- # y=alt.Y('count()', title='Number of Injury-Related Crashes'),
92
- # color=alt.Color('DAY_TYPE:N', legend=alt.Legend(title='Day Type'))
93
- # ).transform_filter(
94
- # selection
95
- # ).properties(
96
- # width=300,
97
- # height=300,
98
- # title='Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend'
99
- # )
100
-
101
-
102
  # Driven plot 2: Fatal Injury Rate of Different Lighting Conditions
103
- bar1 = alt.Chart(traffic_analysis).mark_bar().encode(
 
 
 
 
 
 
 
 
 
 
 
104
  x=alt.X('LIGHTING_CONDITION:N', sort='-y', title='Lighting Condition'),
105
- y=alt.Y('mean(INJURIES_FATAL):Q', scale=alt.Scale(domainMin=0), axis=alt.Axis(format='%'), title='Fatal Injury Rate'),
106
  color=alt.Color('LIGHTING_CONDITION:N',
107
  scale=alt.Scale(
108
  domain=['DARKNESS', 'DARKNESS, LIGHTED ROAD', 'DAWN', 'DUSK', 'DAYLIGHT', 'UNKNOWN'],
109
  range=['#084C88', '#2A6FB6', '#4FA3D9', '#7EC8E3', '#BFEFFF', '#E0F7FA']
 
110
  ),
111
  legend=alt.Legend(orient='left', title='Lighting Condition', titlePadding=15)),
112
  tooltip=[
113
  alt.Tooltip('LIGHTING_CONDITION:N', title='Lighting Condition'),
114
- alt.Tooltip('mean(INJURIES_FATAL):Q', title='Fatal Injury Rate', format='.2f')
115
  ]
116
- ).transform_filter(
117
- selection
118
  ).properties(
119
- width=300,
120
- height=300,
121
- title='Fatal Injury Rate of Different Lighting Conditions'
 
 
 
 
122
  )
123
 
124
-
125
- # bar2 = alt.Chart(traffic_analysis).mark_bar().encode(
126
- # x=alt.X('WEATHER_CONDITION:N'),
127
- # y=alt.Y('mean(INJURIES_FATAL):Q'),
128
- # color=alt.Color('WEATHER_CONDITION:N',
129
- # legend=alt.Legend(orient='right'))
 
 
 
 
 
 
 
 
130
  # ).transform_filter(
131
  # selection
132
  # ).properties(
133
  # width=400,
134
- # height=400
 
 
135
  # )
136
 
137
  # Driven plot 3: Trends in Crash Damage Costs by Year (2018–2024)
138
- grouped_bar = alt.Chart(traffic_analysis).mark_bar().encode(
139
  x=alt.X('YEAR:O', title='Year'),
140
- y=alt.Y('count()', title='Count'),
141
  color=alt.Color('DAMAGE:N',
142
  scale=alt.Scale(
143
  domain=['$500 OR LESS', '$501 - $1,500', 'OVER $1,500'],
144
- range=['#AEDFF7', '#4FA3D9', '#084C88']
 
145
  ),
146
  title='Damage Level', legend=alt.Legend(title='Damage Level', titlePadding=15)),
147
  xOffset='DAMAGE:N',
@@ -153,43 +362,288 @@ grouped_bar = alt.Chart(traffic_analysis).mark_bar().encode(
153
  ).transform_filter(
154
  selection
155
  ).properties(
156
- width=300,
157
- height=300,
158
- title='Annual Distribution of Crash Damage Levels (2018–2024)'
 
 
 
 
159
  )
160
 
161
- top_row = chart|line
162
  bottom_row = (bar1|grouped_bar).resolve_scale(color='independent')
163
- final_chart = top_row & bottom_row
 
 
 
 
 
 
 
 
164
 
165
- # top_row = alt.hconcat(chart, line).resolve_scale(color='independent')
166
- # bottom_row = alt.hconcat(bar1, grouped_bar).resolve_scale(color='independent')
167
 
168
- # final_chart = alt.vconcat(top_row, bottom_row)
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
- st.altair_chart(final_chart, use_container_width=False)
171
 
172
- st.markdown('''
173
- ### Dashboard Overview and Guidance
174
- 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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
- 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.
177
 
178
- 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).
179
 
180
- 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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
- 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.
183
 
184
- 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.
185
- ''')
186
-
187
- st.markdown('''
188
- #### Contexual Dataset
189
- 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.
190
- ''')
191
-
192
- st.markdown('''
193
- #### Hosting Datasets
194
- 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).
195
- ''')
 
 
 
 
 
2
  import pandas as pd
3
  import altair as alt
4
  import streamlit as st
5
+ import geopandas as gpd
6
+ import json
7
+
8
+ st.set_page_config(layout="wide")
9
+
10
+ st.markdown("""
11
+ <style>
12
+ select {
13
+ font-size: 20px !important;
14
+ }
15
+ label {
16
+ font-size: 20px !important;
17
+ }
18
+ </style>
19
+ """, unsafe_allow_html=True)
20
 
21
  @st.cache_data
22
  def load_data():
23
+ df1 = pd.read_csv("https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Traffic_Crashes_-_Crashes_20250420.csv")
24
+ df1 = df1.dropna(subset=['LATITUDE', 'LONGITUDE'])
 
25
 
26
+ # df2 = gpd.read_file('https://data.cityofchicago.org/resource/igwz-8jzy.geojson')
27
+ df2 = gpd.read_file("https://huggingface.co/datasets/Chloecky/traffic_crashes_chicago/resolve/main/Boundaries%20-%20Community%20Areas_20250504.geojson")
28
+
29
+ return df1, df2
30
 
31
+ @st.cache_data
32
+ def preprocess_data():
33
+ traffic, areas = load_data()
34
 
35
+ traffic['CRASH_DATE'] = pd.to_datetime(traffic['CRASH_DATE'])
36
+ traffic['YEAR'] = traffic['CRASH_DATE'].dt.year
37
+ traffic = traffic[
38
+ (traffic['YEAR'].between(2018, 2024)) &
39
+ (traffic['INJURIES_TOTAL'] > 0) &
40
+ (traffic['LONGITUDE'] != 0) & (traffic['LATITUDE'] != 0)
41
+ ]
42
+ traffic['DAY_TYPE'] = traffic['CRASH_DAY_OF_WEEK'].apply(lambda x: 'Weekend' if x in [1, 7] else 'Weekday')
43
 
44
+ areas['geometry_area'] = areas.geometry
45
+ traffic_gdf = gpd.GeoDataFrame(
46
+ traffic,
47
+ geometry=gpd.points_from_xy(traffic['LONGITUDE'], traffic['LATITUDE']),
48
+ crs="EPSG:4326"
49
+ )
50
+ traffic_gdf2 = gpd.sjoin(
51
+ traffic_gdf,
52
+ areas[['area_numbe', 'community', 'geometry', 'geometry_area']],
53
+ how='left',
54
+ predicate='within'
55
+ )
56
 
57
+ polygon_unique = traffic_gdf2[['geometry_area', 'community', 'area_numbe', 'INJURIES_TOTAL', 'YEAR']].dropna().copy()
58
+ polygon_unique = polygon_unique.groupby(['geometry_area', 'community', 'area_numbe', 'YEAR']).agg(
59
+ INJURIES_TOTAL=('INJURIES_TOTAL', 'sum')
60
+ ).reset_index()
61
+ polygon_unique = polygon_unique.set_geometry('geometry_area')
62
+ geojson_data = json.loads(polygon_unique.to_json())
63
 
64
+ return traffic_gdf2, geojson_data
 
 
 
 
 
 
 
65
 
66
+ st.title("🚦 Injured on the Way: An Overview of Chicago Traffic Injuries (2018-2024)")
67
+
68
+ # today = datetime.today().strftime("%B %d, %Y")
69
+ st.markdown(
70
+ f"<span style='font-size:18px; color:black;'>By Keyu (Chloe) Cai, Yutong Zheng | Updated May 05, 2025</span>",
71
+ unsafe_allow_html=True
72
+ )
73
+
74
+ st.markdown("---")
75
+ st.subheader('Understand the Traffic Crash Data in City of Chicago with Us:')
76
+
77
+ # st.title('Streamlit App for IS445 FP3')
78
+ # st.subheader('Created by Keyu (Chloe) Cai and Yutong Zheng')
79
+ # # st.text('Created by Keyu (Chloe) Cai and Yutong Zheng (Group 8)')
80
+ # st.header('Dashboard for Interactive Visualization')
81
+
82
+ st.markdown("""
83
+ <div style='font-size:20px; line-height:1.6; text-align: justify;'>
84
+ Traffic safety is a concern for every city, and Chicago is no exception.
85
+ Every year, more than 100,000 crashes occur on its streets, many of which result in injuries or even fatalities.
86
+ 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.
87
+ We take a closer look at traffic injury data from Chicago between 2018 and 2024 to uncover trends that might help reduce future accidents.
88
+ By turning raw data into clear visualizations, we hope to make these insights more accessible and useful for anyone who cares about safer roads.
89
+ </div>
90
+ """, unsafe_allow_html=True)
91
+
92
+ st.markdown('---')
93
+
94
+ st.markdown("""
95
+ <div style='font-size:22px; font-weight:bold; margin-bottom:10px;'>🚦 Where Injuries Happen Most in Chicago</div>
96
+ <div style='font-size:20px; line-height:1.6; text-align: justify;'>
97
+ 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.
98
+ 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.
99
+ 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.
100
+ </div>
101
+ """, unsafe_allow_html=True)
102
+
103
+ st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
104
+
105
+ st.markdown(
106
+ """
107
+ <div style='font-size:22px; font-weight:bold; margin-bottom:10px;'>🚦 Hourly Crash Patterns: Weekdays vs Weekends</div>
108
+ <div style='font-size:20px; line-height:1.6; text-align: justify;'>
109
+ 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).
110
+ 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.
111
+ In contrast, during late-night and very early morning hours, weekends tend to have more crashes, possibly tied to nightlife or late travel.
112
+ 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.
113
+ </div>
114
+ """,
115
+ unsafe_allow_html=True
116
+ )
117
+
118
+ st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
119
+
120
+ st.markdown(
121
+ """
122
+ <div style='font-size:22px; font-weight:bold; margin-bottom:10px;'>🚦 Fatal Injuries Are More Common in Darker Lighting Conditions</div>
123
+ <div style='font-size:20px; line-height:1.6; text-align: justify;'>
124
+ 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).
125
+ The colors are assigned based on lighting brightness — the darker the lighting condition, the deeper the blue color shade.
126
+ The three most dangerous lighting conditions with the highest fatal injury rates are usually <b>“Darkness, Lighted Road,” “Darkness,”</b> and <b>“Dusk.”</b>
127
+ 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.
128
+ On the other hand, conditions like <b>“Daylight”</b> and <b>“Dawn”</b> tend to have lower fatal injury rates.
129
+ These findings align with common traffic safety concerns—drivers may have longer reaction times or reduced awareness in low-light settings.
130
+ </div>
131
+ """,
132
+ unsafe_allow_html=True
133
+ )
134
+
135
+ st.markdown("<div style='height: 30px;'></div>", unsafe_allow_html=True)
136
+
137
+ st.markdown(
138
+ """
139
+ <div style='font-size:22px; font-weight:bold; margin-bottom:10px;'>🚦 Crash Damage Levels Over the Years</div>
140
+ <div style='font-size:20px; line-height:1.6; text-align: justify;'>
141
+ 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).
142
+ 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.
143
+ In comparison, crashes with less cost (under $1,500) have remained relatively stable or even decreased slightly over time.
144
+ This trend could suggest more serious crashes happening or better reporting of higher-cost accidents.
145
+ 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.
146
+ Factors like road design, local driving behavior, and traffic volume may all play a role.
147
+ </div>
148
+ """,
149
+ unsafe_allow_html=True
150
+ )
151
+
152
+ st.markdown('---')
153
+
154
+ st.subheader('Explore More Through Our Interactive Dashboard!')
155
+ st.markdown("<span style='font-size:18px; color:gray;'>" \
156
+ "Use the dropdown in the bottom-left to select a different year. " \
157
+ "You can also click on different areas in the heatmap to update the other charts based on that specific community.</span>",
158
+ unsafe_allow_html=True)
159
+
160
+ # 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)
161
+
162
+ # traffic, areas = load_data()
163
+
164
+ # # Transform date column
165
+ # traffic['CRASH_DATE'] = pd.to_datetime(traffic['CRASH_DATE'])
166
+
167
+ # # Raw dataset already has 'Hour' and 'Month'
168
+ # traffic['YEAR'] = traffic['CRASH_DATE'].dt.year
169
+ # traffic['DY'] = traffic['CRASH_DATE'].dt.day
170
+
171
+ # traffic_analysis = traffic.loc[:, traffic.columns.isin(['YEAR', 'LONGITUDE', 'LATITUDE', 'CRASH_DAY_OF_WEEK',
172
+ # 'INJURIES_TOTAL', 'CRASH_HOUR', 'LIGHTING_CONDITION',
173
+ # 'DAMAGE','INJURIES_FATAL'])]
174
+ # # Select years with complete records (2018-2024)
175
+ # traffic_analysis = traffic_analysis[(traffic_analysis['YEAR'].isin(range(2018, 2025))) & (traffic_analysis['INJURIES_TOTAL'] > 0)].copy()
176
+ # traffic_analysis = traffic_analysis[(traffic_analysis['LONGITUDE'] != 0) & (traffic_analysis['LATITUDE'] != 0)].copy()
177
+
178
+ # # Add Weekday/Weekend label for each record
179
+ # traffic_analysis['DAY_TYPE'] = traffic_analysis['CRASH_DAY_OF_WEEK'].apply(lambda x: 'Weekend' if x in [1, 7] else 'Weekday')
180
+
181
+ # # Prepare for plotting community areas
182
+ # areas['geometry_area'] = areas.geometry
183
+ # traffic_gdf = gpd.GeoDataFrame(
184
+ # traffic_analysis,
185
+ # geometry=gpd.points_from_xy(traffic_analysis['LONGITUDE'], traffic_analysis['LATITUDE']),
186
+ # crs="EPSG:4326"
187
+ # )
188
+
189
+ # traffic_gdf2 = gpd.sjoin(traffic_gdf, areas[['area_numbe', 'community', 'geometry', 'geometry_area']], how='left', predicate='within')
190
+ # # Deduplicate
191
+ # polygon_unique = traffic_gdf2[['geometry_area', 'community', 'area_numbe', 'INJURIES_TOTAL', 'YEAR']].dropna().copy()
192
+
193
+ # # Aggregation
194
+ # polygon_unique = polygon_unique.groupby(['geometry_area', 'community', 'area_numbe', 'YEAR']
195
+ # ).agg(INJURIES_TOTAL=('INJURIES_TOTAL', 'sum')).reset_index()
196
+
197
+ # polygon_unique = polygon_unique.set_geometry('geometry_area')
198
+ # geojson_data = json.loads(polygon_unique.to_json())
199
+
200
+ traffic_gdf2, geojson_data = preprocess_data()
201
 
 
202
  alt.data_transformers.disable_max_rows()
203
+ selection = alt.selection_point(fields=["area_numbe"])
204
+
205
+ year_selector = alt.selection_single(
206
+ fields=["YEAR"],
207
+ bind=alt.binding_select(
208
+ options=sorted(traffic_gdf2['YEAR'].unique()),
209
+ name='Select Year: '
210
+ )
211
+ )
212
+
213
+ # selected_year = st.selectbox("Select Year: ", sorted(traffic_gdf2["YEAR"].unique()))
214
+
215
+ # filtered_features = [
216
+ # f for f in geojson_data["features"]
217
+ # if f["properties"]["YEAR"] == selected_year
218
+ # ]
219
+
220
+ # filtered_geojson = {"type": "FeatureCollection", "features": filtered_features}
221
+
222
+ # Driver plot: Heatmap of Injuries Total by Location in City of Chicago
223
+ # chart = alt.Chart(alt.Data(values=geojson_data['features'])).mark_geoshape(stroke='white', strokeWidth=0.8).encode(
224
+ chart = alt.Chart(alt.Data(values=geojson_data["features"])).mark_geoshape(stroke='white', strokeWidth=0.8).encode(
225
+ color=alt.condition(
226
+ selection,
227
+ alt.Color('properties.INJURIES_TOTAL:Q',
228
+ scale=alt.Scale(scheme='yellowgreenblue'),
229
+ legend=alt.Legend(orient='left', title='Total Injuries', offset=20, titlePadding=15)),
230
+ alt.value('lightgray')
231
+ ),
232
  tooltip=[
233
+ alt.Tooltip('properties.area_numbe:N', title='Area Number'),
234
+ alt.Tooltip('properties.community:N', title='Community Name'),
235
+ alt.Tooltip('properties.INJURIES_TOTAL:Q', title='Total Injuries')
 
236
  ]
237
+ ).transform_calculate(
238
+ area_numbe='datum.properties.area_numbe',
239
+ YEAR='datum.properties.YEAR'
240
  ).add_params(
241
+ selection,
242
+ year_selector
243
+ ).transform_filter(
244
+ year_selector
245
  ).properties(
246
+ width=350,
247
+ height=350,
248
+ # title='Heatmap of Injuries Total by Location in City of Chicago',
249
+ title=alt.TitleParams(
250
+ text='Heatmap of Total Injuries by Location in City of Chicago',
251
+ anchor='middle'
252
+ )
253
  )
254
 
255
  # Driven plot 1: Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend
256
+ line = alt.Chart(traffic_gdf2.drop(columns=['geometry_area'])).transform_filter(
257
+ selection,
258
+ year_selector
259
  ).transform_aggregate(
260
  crash_count='count()',
261
  groupby=['CRASH_HOUR', 'DAY_TYPE']
 
263
  adjusted_count="datum.DAY_TYPE == 'Weekday' ? datum.crash_count / 5 : datum.crash_count / 2"
264
  ).mark_line(point=True).encode(
265
  x=alt.X('CRASH_HOUR:O', title='Hour of Day'),
266
+ y=alt.Y('adjusted_count:Q', title='Average Number of Injury-Related Crashes', axis=alt.Axis(grid=False)),
267
+ color=alt.Color('DAY_TYPE:N', scale=alt.Scale(
268
+ domain=['Weekday', 'Weekend'],
269
+ range=['#225ea8', '#c7e9b4']
270
+ ), legend=alt.Legend(title='Day Type', titlePadding=15)),
271
  tooltip=[
272
  alt.Tooltip('CRASH_HOUR:O', title='Hour of Day'),
273
  alt.Tooltip('DAY_TYPE:N', title='Day Type'),
274
  alt.Tooltip('adjusted_count:Q', title='Average Count', format=',d')
275
  ]
276
  ).properties(
277
+ width=350,
278
+ height=350,
279
+ # title='Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend',
280
+ title=alt.TitleParams(
281
+ text='Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend',
282
+ anchor='middle'
283
+ )
284
  )
285
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  # Driven plot 2: Fatal Injury Rate of Different Lighting Conditions
287
+ bar1 = alt.Chart(traffic_gdf2.drop(columns=['geometry_area'])).transform_filter(
288
+ selection,
289
+ year_selector
290
+ ).transform_calculate(
291
+ is_fatal="datum.INJURIES_FATAL > 0 ? 1 : 0"
292
+ ).transform_aggregate(
293
+ total='count()',
294
+ fatal='sum(is_fatal)',
295
+ groupby=['LIGHTING_CONDITION']
296
+ ).transform_calculate(
297
+ fatal_rate='datum.fatal / datum.total'
298
+ ).mark_bar().encode(
299
  x=alt.X('LIGHTING_CONDITION:N', sort='-y', title='Lighting Condition'),
300
+ y=alt.Y('fatal_rate:Q', axis=alt.Axis(format='%', grid=False), title='Fatal Injury Rate'),
301
  color=alt.Color('LIGHTING_CONDITION:N',
302
  scale=alt.Scale(
303
  domain=['DARKNESS', 'DARKNESS, LIGHTED ROAD', 'DAWN', 'DUSK', 'DAYLIGHT', 'UNKNOWN'],
304
  range=['#084C88', '#2A6FB6', '#4FA3D9', '#7EC8E3', '#BFEFFF', '#E0F7FA']
305
+ # range=['#253494', '#225ea8', '#1d91c0', '#41b6c4', '#7fcdbb', '#c7e9b4', '#edf8b1']
306
  ),
307
  legend=alt.Legend(orient='left', title='Lighting Condition', titlePadding=15)),
308
  tooltip=[
309
  alt.Tooltip('LIGHTING_CONDITION:N', title='Lighting Condition'),
310
+ alt.Tooltip('fatal_rate:Q', title='Fatal Injury Rate', format='.2%')
311
  ]
 
 
312
  ).properties(
313
+ width=400,
314
+ height=350,
315
+ # title='Fatal Injury Rate of Different Lighting Conditions',
316
+ title=alt.TitleParams(
317
+ text='Fatal Injury Rate of Different Lighting Conditions',
318
+ anchor='middle'
319
+ )
320
  )
321
 
322
+ # Driven plot 2: Fatal Injury Rate of Different Lighting Conditions
323
+ # bar1 = alt.Chart(traffic_gdf2.drop(columns=['geometry_area'])).mark_bar().encode(
324
+ # x=alt.X('LIGHTING_CONDITION:N', sort='-y', title='Lighting Condition'),
325
+ # y=alt.Y('mean(INJURIES_FATAL):Q', scale=alt.Scale(domainMin=0), axis=alt.Axis(format='%'), title='Fatal Injury Rate'),
326
+ # color=alt.Color('LIGHTING_CONDITION:N',
327
+ # scale=alt.Scale(
328
+ # domain=['DARKNESS', 'DARKNESS, LIGHTED ROAD', 'DAWN', 'DUSK', 'DAYLIGHT', 'UNKNOWN'],
329
+ # range=['#084C88', '#2A6FB6', '#4FA3D9', '#7EC8E3', '#BFEFFF', '#E0F7FA']
330
+ # ),
331
+ # legend=alt.Legend(orient='left', title='Lighting Condition', titlePadding=15)),
332
+ # tooltip=[
333
+ # alt.Tooltip('LIGHTING_CONDITION:N', title='Lighting Condition'),
334
+ # alt.Tooltip('mean(INJURIES_FATAL):Q', title='Fatal Injury Rate', format='.2f')
335
+ # ]
336
  # ).transform_filter(
337
  # selection
338
  # ).properties(
339
  # width=400,
340
+ # height=350,
341
+ # title='Fatal Injury Rate of Different Lighting Conditions',
342
+ # anchor='middle'
343
  # )
344
 
345
  # Driven plot 3: Trends in Crash Damage Costs by Year (2018–2024)
346
+ grouped_bar = alt.Chart(traffic_gdf2.drop(columns=['geometry_area'])).mark_bar().encode(
347
  x=alt.X('YEAR:O', title='Year'),
348
+ y=alt.Y('count()', title='Count of Injury-Related Crashes', axis=alt.Axis(grid=False)),
349
  color=alt.Color('DAMAGE:N',
350
  scale=alt.Scale(
351
  domain=['$500 OR LESS', '$501 - $1,500', 'OVER $1,500'],
352
+ # range=['#AEDFF7', '#4FA3D9', '#084C88']
353
+ range=['#c7e9b4', '#0e8fc3', '#084C88']
354
  ),
355
  title='Damage Level', legend=alt.Legend(title='Damage Level', titlePadding=15)),
356
  xOffset='DAMAGE:N',
 
362
  ).transform_filter(
363
  selection
364
  ).properties(
365
+ width=450,
366
+ height=350,
367
+ # title='Annual Distribution of Crash Damage Levels (2018–2024)',
368
+ title=alt.TitleParams(
369
+ text='Annual Distribution of Crash Damage Levels (2018–2024)',
370
+ anchor='middle'
371
+ )
372
  )
373
 
374
+ top_row = (chart|line)
375
  bottom_row = (bar1|grouped_bar).resolve_scale(color='independent')
376
+ final_chart = (top_row & bottom_row).configure_axis(
377
+ labelFontSize=16,
378
+ titleFontSize=20
379
+ ).configure_title(
380
+ fontSize=24
381
+ ).configure_legend(
382
+ labelFontSize=16,
383
+ titleFontSize=18
384
+ )
385
 
386
+ st.altair_chart(final_chart, use_container_width=False)
 
387
 
388
+ # st.markdown('''
389
+ # ### Dashboard Overview and Guidance
390
+ # 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.
391
+
392
+ # 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.
393
+
394
+ # 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).
395
+
396
+ # 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.
397
+
398
+ # 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.
399
+
400
+ # 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.
401
+ # ''')
402
 
 
403
 
404
+ st.markdown('---')
405
+
406
+ st.subheader('Contextual Visualization from Other Sources')
407
+
408
+ st.image('https://miro.medium.com/v2/resize:fit:640/format:webp/1*2wHu-JlqN-KHQ9mvzlog9Q.png',
409
+ caption='Viz 1: Density of Injured and Killed per Borough, by Area in New York City, 2013-2019',
410
+ width = 500)
411
+ 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',
412
+ caption='Viz 2: Fatal/Serious vs Other Injuries in San Antonio City, 2011-2021',
413
+ width = 600)
414
+ st.image('Viz3.png',
415
+ caption='Viz 3: Traffic Fatalities, by Rural/Urban Classification, 2013-2022 (United States)',
416
+ width = 600)
417
+ st.image('Viz4.png',
418
+ caption='Viz 4: Fatality Rates per 100 Million VMT, by State, 2022',
419
+ width = 600)
420
+
421
+ st.markdown('---')
422
+
423
+ st.subheader('Check out the Raw Data and Related Sources If Interested:')
424
+
425
+ st.markdown("""
426
+ <div style='font-size:22px; margin-top:15px; font-weight:bold;'>Datasets are hosted on HuggingFace for our application:</div>
427
+
428
+ <div style='font-size:20px;'>
429
+ <ul>
430
+ <li>
431
+ <b>Data 1:</b>
432
+ <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>
433
+ </li>
434
+
435
+ <li>
436
+ <b>Data 2:</b>
437
+ <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>
438
+ </li>
439
+ </ul>
440
+ </div>
441
+ """, unsafe_allow_html=True)
442
+
443
+ # st.markdown('''
444
+ # Citations:
445
 
446
+ # Viz 1: https://joycegemcanete.medium.com/simple-analysis-of-the-new-york-motor-vehicle-collision-dataset-c6f883646560 ,
447
 
448
+ # 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
449
 
450
+ # 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.
451
+ # [Link to original publication](https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813560)
452
+ # ''')
453
+
454
+ st.markdown("""
455
+ <div style='font-size:22px; margin-top:15px; font-weight:bold;'>Citations:</div>
456
+
457
+ <div style='font-size:20px;'>
458
+ <ul>
459
+ <li>
460
+ <b>Viz 1:</b> Canete, J. G. (2023, June 8). <i>Simple analysis of the New York motor vehicle collision dataset</i>. Medium.
461
+ <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>
462
+ </li>
463
+
464
+ <li>
465
+ <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.
466
+ <a href="https://doi.org/10.46810/tdfd.1136432" target="_blank">https://doi.org/10.46810/tdfd.1136432</a>
467
+ </li>
468
+
469
+ <li>
470
+ <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.
471
+ <a href="https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813560" target="_blank">https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813560</a>
472
+ </li>
473
+
474
+ <li>
475
+ <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.
476
+ <a href="https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813643" target="_blank">https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/813643</a>
477
+ </li>
478
+
479
+ <li>
480
+ <b>Data 1:</b> City of Chicago. (n.d.). <i>Traffic Crashes - Crashes. </i> Chicago Data Portal. Retrieved April 20, 2025, from
481
+ <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>
482
+ </li>
483
+
484
+ <li>
485
+ <b>Data 2:</b> City of Chicago. (n.d.). <i>Boundaries - Community Areas. </i> Chicago Data Portal. Retrieved May 4, 2025, from
486
+ <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>
487
+ </li>
488
+ </ul>
489
+ </div>
490
+ """, unsafe_allow_html=True)
491
+
492
+ # # Driver plot: Heatmap of Injuries Total by Location in City of Chicago
493
+ # alt.data_transformers.disable_max_rows()
494
+ # selection = alt.selection_interval(encodings=['x','y'])
495
+ # chart = alt.Chart(traffic_analysis).mark_rect().encode(
496
+ # x=alt.X('LONGITUDE:Q', bin=alt.Bin(maxbins=20), title='Longitude (°)'),
497
+ # y=alt.Y('LATITUDE:Q', bin=alt.Bin(maxbins=20), title='Latitude (°)'),
498
+ # color=alt.Color('sum(INJURIES_TOTAL):Q',
499
+ # scale=alt.Scale(scheme='blues'),
500
+ # title='Injuries Total',
501
+ # legend=alt.Legend(orient='left', offset=20, titlePadding=15)),
502
+ # tooltip=[
503
+ # alt.Tooltip('count()', title='Crash Count'),
504
+ # alt.Tooltip('sum(INJURIES_TOTAL):Q', title='Injuries Total'),
505
+ # alt.Tooltip('LATITUDE:Q', bin=True, title='Latitude bin'),
506
+ # alt.Tooltip('LONGITUDE:Q', bin=True, title='Longitude bin')
507
+ # ]
508
+ # ).add_params(
509
+ # selection
510
+ # ).properties(
511
+ # width=300,
512
+ # height=300,
513
+ # title='Heatmap of Injuries Total by Location in City of Chicago'
514
+ # title=alt.TitleParams(
515
+ # text='Heatmap of Injuries Total by Location in City of Chicago',
516
+ # anchor='middle' # <<< 关键在这里,anchor设成'middle'就是居中!
517
+ # )
518
+ # )
519
+
520
+ # # Driven plot 1: Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend
521
+ # line = alt.Chart(traffic_analysis).transform_filter(
522
+ # selection
523
+ # ).transform_aggregate(
524
+ # crash_count='count()',
525
+ # groupby=['CRASH_HOUR', 'DAY_TYPE']
526
+ # ).transform_calculate(
527
+ # adjusted_count="datum.DAY_TYPE == 'Weekday' ? datum.crash_count / 5 : datum.crash_count / 2"
528
+ # ).mark_line(point=True).encode(
529
+ # x=alt.X('CRASH_HOUR:O', title='Hour of Day'),
530
+ # y=alt.Y('adjusted_count:Q', title='Average Number of Injury-Related Crashes'),
531
+ # color=alt.Color('DAY_TYPE:N', legend=alt.Legend(title='Day Type', titlePadding=15)),
532
+ # tooltip=[
533
+ # alt.Tooltip('CRASH_HOUR:O', title='Hour of Day'),
534
+ # alt.Tooltip('DAY_TYPE:N', title='Day Type'),
535
+ # alt.Tooltip('adjusted_count:Q', title='Average Count', format=',d')
536
+ # ]
537
+ # ).properties(
538
+ # width=300,
539
+ # height=300,
540
+ # title='Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend'
541
+ # )
542
+
543
+ # # line = alt.Chart(traffic_analysis).mark_line(point=True).encode(
544
+ # # x=alt.X('CRASH_HOUR:O', title='Hour of Day'),
545
+ # # y=alt.Y('count()', title='Number of Injury-Related Crashes'),
546
+ # # color=alt.Color('DAY_TYPE:N', legend=alt.Legend(title='Day Type'))
547
+ # # ).transform_filter(
548
+ # # selection
549
+ # # ).properties(
550
+ # # width=300,
551
+ # # height=300,
552
+ # # title='Hourly Distribution of Injury-Related Crashes: Weekday vs Weekend'
553
+ # # )
554
+
555
+
556
+ # # Driven plot 2: Fatal Injury Rate of Different Lighting Conditions
557
+ # bar1 = alt.Chart(traffic_analysis).mark_bar().encode(
558
+ # x=alt.X('LIGHTING_CONDITION:N', sort='-y', title='Lighting Condition'),
559
+ # y=alt.Y('mean(INJURIES_FATAL):Q', scale=alt.Scale(domainMin=0), axis=alt.Axis(format='%'), title='Fatal Injury Rate'),
560
+ # color=alt.Color('LIGHTING_CONDITION:N',
561
+ # scale=alt.Scale(
562
+ # domain=['DARKNESS', 'DARKNESS, LIGHTED ROAD', 'DAWN', 'DUSK', 'DAYLIGHT', 'UNKNOWN'],
563
+ # range=['#084C88', '#2A6FB6', '#4FA3D9', '#7EC8E3', '#BFEFFF', '#E0F7FA']
564
+ # ),
565
+ # legend=alt.Legend(orient='left', title='Lighting Condition', titlePadding=15)),
566
+ # tooltip=[
567
+ # alt.Tooltip('LIGHTING_CONDITION:N', title='Lighting Condition'),
568
+ # alt.Tooltip('mean(INJURIES_FATAL):Q', title='Fatal Injury Rate', format='.2f')
569
+ # ]
570
+ # ).transform_filter(
571
+ # selection
572
+ # ).properties(
573
+ # width=300,
574
+ # height=300,
575
+ # title='Fatal Injury Rate of Different Lighting Conditions'
576
+ # )
577
+
578
+
579
+ # # bar2 = alt.Chart(traffic_analysis).mark_bar().encode(
580
+ # # x=alt.X('WEATHER_CONDITION:N'),
581
+ # # y=alt.Y('mean(INJURIES_FATAL):Q'),
582
+ # # color=alt.Color('WEATHER_CONDITION:N',
583
+ # # legend=alt.Legend(orient='right'))
584
+ # # ).transform_filter(
585
+ # # selection
586
+ # # ).properties(
587
+ # # width=400,
588
+ # # height=400
589
+ # # )
590
+
591
+ # # Driven plot 3: Trends in Crash Damage Costs by Year (2018–2024)
592
+ # grouped_bar = alt.Chart(traffic_analysis).mark_bar().encode(
593
+ # x=alt.X('YEAR:O', title='Year'),
594
+ # y=alt.Y('count()', title='Count'),
595
+ # color=alt.Color('DAMAGE:N',
596
+ # scale=alt.Scale(
597
+ # domain=['$500 OR LESS', '$501 - $1,500', 'OVER $1,500'],
598
+ # range=['#AEDFF7', '#4FA3D9', '#084C88']
599
+ # ),
600
+ # title='Damage Level', legend=alt.Legend(title='Damage Level', titlePadding=15)),
601
+ # xOffset='DAMAGE:N',
602
+ # tooltip=[
603
+ # alt.Tooltip('YEAR:O', title='Year'),
604
+ # alt.Tooltip('DAMAGE:N', title='Damage Level'),
605
+ # alt.Tooltip('count()', title='Count')
606
+ # ]
607
+ # ).transform_filter(
608
+ # selection
609
+ # ).properties(
610
+ # width=300,
611
+ # height=300,
612
+ # title='Annual Distribution of Crash Damage Levels (2018–2024)'
613
+ # )
614
+
615
+ # top_row = chart|line
616
+ # bottom_row = (bar1|grouped_bar).resolve_scale(color='independent')
617
+ # final_chart = top_row & bottom_row
618
+
619
+ # # top_row = alt.hconcat(chart, line).resolve_scale(color='independent')
620
+ # # bottom_row = alt.hconcat(bar1, grouped_bar).resolve_scale(color='independent')
621
+
622
+ # # final_chart = alt.vconcat(top_row, bottom_row)
623
+
624
+ # st.altair_chart(final_chart, use_container_width=False)
625
+
626
+ # st.markdown('''
627
+ # ### Dashboard Overview and Guidance
628
+ # 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.
629
+
630
+ # 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.
631
 
632
+ # 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).
633
 
634
+ # 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.
635
+
636
+ # 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.
637
+
638
+ # 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.
639
+ # ''')
640
+
641
+ # st.markdown('''
642
+ # #### Contexual Dataset
643
+ # 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.
644
+ # ''')
645
+
646
+ # st.markdown('''
647
+ # #### Hosting Datasets
648
+ # 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).
649
+ # ''')