Nirmal16 commited on
Commit
4945824
·
verified ·
1 Parent(s): ce187da

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +753 -8
app.py CHANGED
@@ -1,15 +1,760 @@
1
  import streamlit as st
 
 
 
 
 
 
 
2
 
3
- st.title("My First Streamlit App")
 
 
 
 
 
 
 
 
 
4
 
5
- st.write("Hello, Streamlit!")
 
 
 
 
 
 
 
6
 
7
- name = st.text_input("Enter your name:")
8
- if name:
9
- st.write("Hello,", name)
10
 
11
- # # /Users/nirmal/Library/Python/3.9/lib/python/site-packages
12
- # # export PATH="/Users/nirmal/Library/Python/3.9/lib/python/site-packages:$PATHcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- # print("hi")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ import altair as alt
5
+ import folium
6
+ from streamlit_plotly_events import plotly_events # added for part3 interactivity
7
+ from folium.plugins import HeatMap, MarkerCluster
8
+ from streamlit_folium import st_folium
9
 
10
+ # To fix the color scheme in crash stats plot (asked ChatGPT for appropriate colors)
11
+ severity_colors = {
12
+ "No Injury": "#1f77b4",
13
+ "Possible Injury": "#aec7e8",
14
+ "Non Incapacitating Injury": "#ff7f0e",
15
+ "Incapacitating Injury": "#ffbb78",
16
+ "Suspected Minor Injury": "#2ca02c",
17
+ "Suspected Serious Injury": "#98df8a",
18
+ "Fatal": "#d62728",
19
+ }
20
 
21
+ @st.cache_data
22
+ def load_and_preprocess_data(file_path):
23
+ # Read the data
24
+ df = pd.read_csv(file_path)
25
+
26
+ # Basic preprocessing
27
+ df = df.drop(['X', 'Y'], axis=1)
28
+ df.dropna(subset=['Incidentid', 'DateTime', 'Year', 'Latitude', 'Longitude'], inplace=True)
29
 
30
+ # Convert Year to int
31
+ df['Year'] = df['Year'].astype(int)
 
32
 
33
+ # Fill missing values
34
+ numeric = ['Age_Drv1', 'Age_Drv2']
35
+ for col in numeric:
36
+ df[col].fillna(df[col].median(), inplace=True)
37
+
38
+ categorical = ['Gender_Drv1', 'Violation1_Drv1', 'AlcoholUse_Drv1', 'DrugUse_Drv1',
39
+ 'Gender_Drv2', 'Violation1_Drv2', 'AlcoholUse_Drv2', 'DrugUse_Drv2',
40
+ 'Unittype_Two', 'Traveldirection_Two', 'Unitaction_Two', 'CrossStreet']
41
+ for col in categorical:
42
+ df[col].fillna('Unknown', inplace=True)
43
+
44
+ # Remove invalid ages
45
+ df = df[
46
+ (df['Age_Drv1'] <= 90) &
47
+ (df['Age_Drv2'] <= 90) &
48
+ (df['Age_Drv1'] >= 16) &
49
+ (df['Age_Drv2'] >= 16)
50
+ ]
51
+
52
+ # Create age groups
53
+ bins = [15, 25, 35, 45, 55, 65, 90]
54
+ labels = ['16-25', '26-35', '36-45', '46-55', '56-65', '65+']
55
+
56
+ df['Age_Group_Drv1'] = pd.cut(df['Age_Drv1'], bins=bins, labels=labels)
57
+ df['Age_Group_Drv2'] = pd.cut(df['Age_Drv2'], bins=bins, labels=labels)
58
+
59
+ return df
60
 
61
+ def create_severity_violation_chart(df, age_group=None):
62
+ # Apply age group filter if selected
63
+ if age_group != 'All Ages':
64
+ df = df[(df['Age_Group_Drv1'] == age_group) | (df['Age_Group_Drv2'] == age_group)]
65
+
66
+ # Combine violations from both drivers
67
+ violations_1 = df.groupby(['Violation1_Drv1', 'Injuryseverity']).size().reset_index(name='count')
68
+ violations_2 = df.groupby(['Violation1_Drv2', 'Injuryseverity']).size().reset_index(name='count')
69
+
70
+ violations_1.columns = ['Violation', 'Severity', 'count']
71
+ violations_2.columns = ['Violation', 'Severity', 'count']
72
+
73
+ violations = pd.concat([violations_1, violations_2])
74
+ violations = violations.groupby(['Violation', 'Severity'])['count'].sum().reset_index()
75
+
76
+ # Create visualization
77
+ fig = px.bar(
78
+ violations,
79
+ x='Violation',
80
+ y='count',
81
+ color='Severity',
82
+ title=f'Crash Severity Distribution by Violation Type - {age_group}',
83
+ labels={'count': 'Number of Incidents', 'Violation': 'Violation Type'},
84
+ height=600,
85
+ color_discrete_map=severity_colors, # --> for part 3
86
+ )
87
+
88
+ # fig.update_layout(
89
+ # xaxis_tickangle=-45,
90
+ # legend_title='Severity Level',
91
+ # barmode='stack'
92
+ # )
93
 
94
+ # modified the above code because x-axis labels were partially pruned
95
+ fig.update_layout(
96
+ xaxis_tickangle=-45,
97
+ legend_title='Severity Level',
98
+ barmode='stack',
99
+ margin=dict(t=50, b=150), # Increase bottom margin to avoid pruning
100
+ xaxis=dict(automargin=True)
101
+ )
102
+
103
+ # return fig
104
+ return fig, violations
105
+
106
+ def get_top_violations(df, age_group):
107
+ # Calculate total incidents for the age group
108
+ if age_group == 'All Ages':
109
+ total_incidents = len(df)
110
+ # Get violations for all ages
111
+ violations = pd.concat([
112
+ df['Violation1_Drv1'].value_counts(),
113
+ df['Violation1_Drv2'].value_counts()
114
+ ]).groupby(level=0).sum()
115
+ else:
116
+ # Filter for specific age group
117
+ filtered_df = df[
118
+ (df['Age_Group_Drv1'] == age_group) |
119
+ (df['Age_Group_Drv2'] == age_group)
120
+ ]
121
+ total_incidents = len(filtered_df)
122
+ # Get violations for specific age group
123
+ violations = pd.concat([
124
+ filtered_df['Violation1_Drv1'].value_counts(),
125
+ filtered_df['Violation1_Drv2'].value_counts()
126
+ ]).groupby(level=0).sum()
127
+
128
+ # Convert to DataFrame and format
129
+ violations_df = violations.reset_index()
130
+ violations_df.columns = ['Violation Type', 'Count']
131
+
132
+ # Sort by Count in descending order
133
+ violations_df = violations_df.sort_values('Count', ascending=False)
134
+
135
+ # Calculate percentage of total incidents
136
+ violations_df['Percentage'] = (violations_df['Count'] / total_incidents * 100).round(2)
137
+ violations_df['Percentage'] = violations_df['Percentage'].map('{:.2f}%'.format)
138
+
139
+ return violations_df.head()
140
+
141
+ @st.cache_data
142
+ def create_interactive_pie_chart(violations, selected_violation, selected_age):
143
+ # Filter data based on selected violation
144
+ filtered_data = violations[violations['Violation'] == selected_violation]
145
+
146
+ # Create a pie chart for severity distribution of the selected violation type
147
+ fig = px.pie(
148
+ filtered_data,
149
+ names='Severity',
150
+ values='count',
151
+ # title=f'Severity Level Distribution for Violation: {selected_violation}',
152
+ title=f'Severity Level Distribution for Violation: {selected_violation} - {selected_age}', # dynamically update pie chart's title
153
+ height=600,
154
+ color_discrete_map=severity_colors
155
+ )
156
+
157
+ return fig
158
+
159
+ def create_map_bar_chart(df, selected_year):
160
+ # Create severity count bar chart
161
+ filtered_df = df[df['Year'] == selected_year]
162
+ severity_count = filtered_df['Injuryseverity'].value_counts().reset_index()
163
+ severity_count.columns = ['Injuryseverity', 'Count']
164
+
165
+ fig = px.bar(
166
+ severity_count,
167
+ x='Injuryseverity',
168
+ y='Count',
169
+ title="Accidents by Severity",
170
+ labels={'Injuryseverity': 'Severity', 'Count': 'Number of Accidents'} # Adjust height as needed
171
+ )
172
+ fig.update_traces(marker_color='blue')
173
+ fig.update_layout(
174
+ clickmode='event+select', # Enable interactivity
175
+ xaxis_tickangle=45, # Rotate x-axis labels 45 degrees
176
+ margin=dict(t=50, b=150), # Add bottom margin to prevent label cutoff
177
+ )
178
+ return fig
179
+
180
+
181
+ @st.cache_data
182
+ def create_map(df, selected_year, selected_severity=None):
183
+ # Filter data by selected year
184
+ filtered_df = df[df['Year'] == selected_year]
185
+
186
+ # Filter further by selected severity if provided
187
+ if selected_severity:
188
+ filtered_df = filtered_df[filtered_df['Injuryseverity'] == selected_severity]
189
+
190
+ # Remove rows with missing latitude or longitude
191
+ filtered_df = filtered_df.dropna(subset=['Latitude', 'Longitude'])
192
+
193
+ # Create the map
194
+ m = folium.Map(
195
+ location=[33.4255, -111.9400], # Default location (can be customized)
196
+ zoom_start=12,
197
+ control_scale=True,
198
+ tiles='CartoDB positron'
199
+ )
200
+
201
+ # Add marker cluster
202
+ marker_cluster = MarkerCluster(name="Accident Locations").add_to(m)
203
+
204
+ # Add accident markers
205
+ for _, row in filtered_df.iterrows():
206
+ folium.Marker(
207
+ location=[row['Latitude'], row['Longitude']],
208
+ popup=f"Accident at {row['Longitude']}, {row['Latitude']}<br>Date: {row['DateTime']}<br>Severity: {row['Injuryseverity']}",
209
+ icon=folium.Icon(color='red')
210
+ ).add_to(marker_cluster)
211
+
212
+ # Add heatmap
213
+ heat_data = filtered_df[['Latitude', 'Longitude']].values.tolist()
214
+ HeatMap(heat_data, radius=15, max_zoom=13, min_opacity=0.3, name="Heat Map").add_to(m)
215
+
216
+ folium.LayerControl().add_to(m)
217
+ return m
218
+
219
+ def create_injuries_fatalities_chart(crash_data, unit_type):
220
+
221
+ # 5th visualization title
222
+ # st.header("5. Total Injuries and Fatalities by Month")
223
+
224
+ # Filter rows where we have valid data for all necessary columns
225
+ crash_data = crash_data[['DateTime', 'Totalinjuries', 'Totalfatalities', 'Unittype_One', 'Unittype_Two']].dropna()
226
+
227
+ # Convert "DateTime" to datetime type
228
+ crash_data['DateTime'] = pd.to_datetime(crash_data['DateTime'], errors='coerce')
229
+ crash_data['Month'] = crash_data['DateTime'].dt.month_name()
230
+
231
+ # sort months in order
232
+ month_order = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
233
+ crash_data['Month'] = pd.Categorical(crash_data['Month'], categories=month_order, ordered=True)
234
+
235
+ # Dropdown for Unit Type selection
236
+ # Dropdown for Unit Type selection
237
+ # st.sidebar.selectbox("Select Unit Type", options=['Total'] + crash_data['Unittype_One'].dropna().unique().tolist()) # previous location of dropdown in sidebar
238
+ # unit_type = st.selectbox("Select Unit Type", options=['Total'] + crash_data['Unittype_One'].dropna().unique().tolist())
239
+ # unit_type_pairs = set()
240
+ # for _, row in crash_data[['Unittype_One', 'Unittype_Two']].dropna().iterrows():
241
+ # if row['Unittype_One'] != 'Driverless' or row['Unittype_Two'] != 'Driverless':
242
+ # pair = ' vs '.join(sorted([row['Unittype_One'], row['Unittype_Two']]))
243
+ # unit_type_pairs.add(pair)
244
+ # # unit_type_pairs = list(unit_type_pairs) # modified as below to sort the dropdown options in alphabetical order
245
+ # unit_type_pairs = sorted(list(unit_type_pairs))
246
+ # unit_type = st.selectbox("Select Unit Type Pair", options=['Total'] + unit_type_pairs)
247
+
248
+ # Filter data based on the selected unit type
249
+ if unit_type == 'Total':
250
+ filtered_data = crash_data
251
+ else:
252
+ unit_one, unit_two = unit_type.split(' vs ')
253
+ filtered_data = crash_data[((crash_data['Unittype_One'] == unit_one) & (crash_data['Unittype_Two'] == unit_two)) |
254
+ ((crash_data['Unittype_One'] == unit_two) & (crash_data['Unittype_Two'] == unit_one))]
255
+
256
+ # Group data by month and calculate total injuries and fatalities
257
+ monthly_sum = filtered_data.groupby('Month').agg({'Totalinjuries': 'sum', 'Totalfatalities': 'sum'}).reset_index()
258
+
259
+ # Reshape the data for easier plotting
260
+ injuries = monthly_sum[['Month', 'Totalinjuries']].rename(columns={'Totalinjuries': 'Value'})
261
+ injuries['Measure'] = 'Total Injuries'
262
+
263
+ fatalities = monthly_sum[['Month', 'Totalfatalities']].rename(columns={'Totalfatalities': 'Value'})
264
+ fatalities['Measure'] = 'Total Fatalities'
265
+
266
+ combined_data = pd.concat([injuries, fatalities])
267
+
268
+ # Originally tried to use bar chart but switched to line chart for better trend visualization
269
+ # alt.Chart(monthly_sum).mark_bar().encode(
270
+ # x=alt.X('Month', sort=month_order, title='Month'),
271
+ # y=alt.Y('Totalinjuries', title='Total Injuries', axis=alt.Axis(titleColor='blue', labelColor='blue', tickColor='blue')),
272
+ # color=alt.value('blue'),
273
+ # tooltip=['Month', 'Totalinjuries']
274
+ # ).properties(
275
+ # title='Total Injuries and Fatalities by Month',
276
+ # width=300,
277
+ # height=300
278
+ # ) + alt.Chart(monthly_sum).mark_bar().encode(
279
+ # x=alt.X('Month', sort=month_order, title='Month'),
280
+ # y=alt.Y('Totalfatalities', title='Total Fatalities', axis=alt.Axis(titleColor='red', labelColor='red', tickColor='red')),
281
+ # color=alt.value('red'),
282
+ # tooltip=['Month', 'Totalfatalities']
283
+ # )
284
+
285
+ # Tried to figure out how to plot a legend using altair
286
+ # line_chart = alt.Chart(monthly_sum).mark_line(point=True).encode(
287
+ # x=alt.X('Month', sort=month_order, title='Month'),
288
+ # y=alt.Y('Totalinjuries', title='Total Injuries & Fatalities', axis=alt.Axis(titleColor='black')),
289
+ # color=alt.value('blue'),
290
+ # tooltip=['Month', 'Totalinjuries']
291
+ # ).properties(
292
+ # title=f'Total Injuries and Fatalities by Month for Unit Type Pair: {unit_type}',
293
+ # width=600,
294
+ # height=400
295
+ # ) + alt.Chart(monthly_sum).mark_line(point=True).encode(
296
+ # x=alt.X('Month', sort=month_order, title='Month'),
297
+ # y=alt.Y('Totalfatalities', axis=alt.Axis(titleColor='red')),
298
+ # color=alt.value('red'),
299
+ # tooltip=['Month', 'Totalfatalities']
300
+ # ).configure_legend(
301
+ # titleFontSize=14,
302
+ # labelFontSize=12,
303
+ # titleColor='black',
304
+ # labelColor='black'
305
+ # )
306
+
307
+ # Plot line chart
308
+ line_chart = alt.Chart(combined_data).mark_line(point=True).encode(
309
+ x=alt.X('Month:N', sort=month_order, title='Month'),
310
+ y=alt.Y('Value:Q', title='Total Injuries & Fatalities'),
311
+ color=alt.Color('Measure:N', title='', scale=alt.Scale(domain=['Total Injuries', 'Total Fatalities'], range=['blue', 'red'])),
312
+ tooltip=['Month', 'Measure:N', 'Value:Q']
313
+ ).properties(
314
+ title=f'Total Injuries and Fatalities by Month for Unit Type Pair: {unit_type}',
315
+ width=600,
316
+ height=400
317
+ )
318
+
319
+ # # Combine the charts (trying to make legend)
320
+ # combined_chart = alt.layer(line_chart_injuries, line_chart_fatalities).properties(
321
+ # title=f'Total Injuries and Fatalities by Month for Unit Type Pair: {unit_type}',
322
+ # width=600,
323
+ # height=400
324
+ # ).configure_legend(
325
+ # titleFontSize=14,
326
+ # labelFontSize=12,
327
+ # titleColor='black',
328
+ # labelColor='black'
329
+ # )
330
+
331
+ return line_chart
332
+
333
+ def create_crash_trend_chart(df, weather=None):
334
+ if weather and weather != 'All Conditions':
335
+ df = df[df['Weather'] == weather]
336
+
337
+ # Group data by year and count unique Incident IDs
338
+ trend_data = df.groupby('Year')['Incidentid'].nunique().reset_index()
339
+ trend_data.columns = ['Year', 'Crash Count']
340
+
341
+ # Create line graph
342
+ fig = px.line(
343
+ trend_data,
344
+ x='Year',
345
+ y='Crash Count',
346
+ title=f'Crash Trend Over Time ({weather})',
347
+ labels={'Year': 'Year', 'Crash Count': 'Number of Unique Crashes'},
348
+ markers=True,
349
+ height=600
350
+ )
351
+
352
+ fig.update_traces(line=dict(width=2), marker=dict(size=8))
353
+ fig.update_layout(legend_title_text='Trend')
354
+
355
+ return fig
356
+
357
+ def create_category_distribution_chart(df, selected_category, selected_year):
358
+ # Filter by selected year
359
+ if selected_year != 'All Years':
360
+ df = df[df['Year'] == int(selected_year)]
361
+
362
+ # Group by selected category and Injury Severity
363
+ grouped_data = df.groupby([selected_category, 'Injuryseverity']).size().reset_index(name='Count')
364
+
365
+ # Calculate percentages for each category value
366
+ total_counts = grouped_data.groupby(selected_category)['Count'].transform('sum')
367
+ grouped_data['Percentage'] = (grouped_data['Count'] / total_counts * 100).round(2)
368
+
369
+ # Create the stacked bar chart using Plotly
370
+ fig = px.bar(
371
+ grouped_data,
372
+ x=selected_category,
373
+ y='Count',
374
+ color='Injuryseverity',
375
+ text='Percentage',
376
+ title=f'Distribution of Incidents by {selected_category} ({selected_year})',
377
+ labels={'Count': 'Number of Incidents', selected_category: 'Category'},
378
+ height=600,
379
+ )
380
+
381
+ # Customize the chart appearance
382
+ fig.update_traces(texttemplate='%{text}%', textposition='inside')
383
+ fig.update_layout(
384
+ barmode='stack',
385
+ xaxis_tickangle=-45,
386
+ legend_title='Injury Severity',
387
+ margin=dict(t=50, b=150, l=50, r=50),
388
+ )
389
+
390
+ return fig
391
+
392
+ def main():
393
+ st.set_page_config(page_title="Terrific Tempe Traffic", layout="wide")
394
+
395
+ st.markdown("""
396
+ <style>
397
+ .reportview-container {
398
+ font-size: 20px;
399
+ }
400
+ h1, h2, h3, h4, h5, h6 {
401
+ font-size: 150%;
402
+ }
403
+ p {
404
+ font-size: 125%;
405
+ }
406
+ </style>
407
+ """, unsafe_allow_html=True)
408
+
409
+
410
+ st.markdown("""
411
+ <style>
412
+ .title {
413
+ text-align: center;
414
+ padding: 25px;
415
+ }
416
+ </style>
417
+ """, unsafe_allow_html=True)
418
+
419
+ st.markdown("<div class='title'><h1> Accident Analysis for City of Tempe,Arizona </h1></div>", unsafe_allow_html=True)
420
+
421
+
422
+ st.markdown("""
423
+ **Team Members:**
424
+ - Janhavi Tushar Zarapkar ([email protected])
425
+ - Hangyue Zhang ([email protected])
426
+ - Andrew Nam ([email protected])
427
+ - Nirmal Attarde ([email protected])
428
+ - Maanas Sandeep Agrawal ([email protected])
429
+ """)
430
+
431
+
432
+ st.markdown("""
433
+ # Introduction to the Traffic Accident Dataset
434
+ 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.
435
+
436
+ 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.
437
+ """)
438
+
439
+
440
+
441
+ # Load data
442
+ df = load_and_preprocess_data('1.08_Crash_Data_Report_(detail).csv')
443
+
444
+ if 'Weather' not in df.columns:
445
+ df['Weather'] = 'Unknown'
446
+
447
+ if 'selected_violation' not in st.session_state:
448
+ st.session_state['selected_violation'] = None
449
+
450
+ if "selected_severity" not in st.session_state:
451
+ st.session_state["selected_severity"] = None
452
+
453
+
454
+ # Create tabs for different visualizations
455
+ tab1, tab2, tab3, tab4, tab5 = st.tabs([
456
+ "Crash Trend",
457
+ "Violation-Severity Analysis",
458
+ "Distribution by Category",
459
+ "Crash Injuries/Fatalities",
460
+ "Severity-Location Analysis"
461
+ ])
462
+
463
+ with tab1:
464
+ # Weather condition filter
465
+ weather = ['All Conditions'] + sorted(df['Weather'].unique())
466
+ selected_weather = st.selectbox('Select Weather Condition:', weather)
467
+
468
+ trend_col, desc_col = st.columns([7, 3])
469
+
470
+ with trend_col:
471
+ trend_fig = create_crash_trend_chart(df, selected_weather)
472
+ trend_fig.update_layout(
473
+ height=800,
474
+ width=None,
475
+ margin=dict(l=50, r=50, t=50, b=50)
476
+ )
477
+ st.plotly_chart(trend_fig, use_container_width=True)
478
+
479
+
480
+
481
+ with desc_col:
482
+ st.markdown("""
483
+ ## **Crash Trend Over Time**
484
+ 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.
485
+
486
+ **Key Features:**
487
+ * **Time Trend Analysis**: Displays the total number of unique crashes for each year, showing long-term patterns.
488
+ * **Weather Filter**: Users can filter the data by weather conditions (e.g., "Rainy", "Sunny") to analyze how weather impacts crash trends.
489
+ * **Interactive Tooltips**: Hovering over data points reveals the exact crash count for each year, providing detailed insights.
490
+
491
+ **Color Scheme and Design:**
492
+ * **Line and Markers**: A smooth line connects data points, with prominent markers for each year to highlight trends clearly.
493
+ * **Dynamic Title**: The chart updates its title to reflect the selected weather condition or "All Conditions" for the overall trend.
494
+
495
+ **Insights:**
496
+
497
+ This chart helps uncover:
498
+ * Annual fluctuations in crash incidents.
499
+ * Correlations between weather conditions and crash frequencies.
500
+ * Historical patterns that can guide future safety measures and urban planning decisions
501
+ """)
502
+
503
+ with tab2:
504
+
505
+ age_groups = ['All Ages', '16-25', '26-35', '36-45', '46-55', '56-65', '65+']
506
+ selected_age = st.selectbox('Select Age Group:', age_groups)
507
+
508
+ trend_col, desc_col = st.columns([6, 4])
509
+
510
+ with trend_col:
511
+ # Create and display main chart
512
+ fig, violations = create_severity_violation_chart(df, selected_age)
513
+
514
+ # Display the chart with selection events enabled
515
+ chart_event = st.plotly_chart(
516
+ fig,
517
+ use_container_width=True,
518
+ key="violation_chart",
519
+ on_select="rerun"
520
+ )
521
+
522
+ # Check if there's a selection event
523
+ if chart_event and chart_event.selection and chart_event.selection.points:
524
+ # Get the selected violation type
525
+ selected_violation = chart_event.selection.points[0]['x']
526
+ # Create and display pie chart for selected violation
527
+ pie_chart = create_interactive_pie_chart(violations, selected_violation, selected_age)
528
+ st.plotly_chart(pie_chart, use_container_width=True)
529
+
530
+ # # Display statistics
531
+ # if selected_age == 'All Ages':
532
+ # total_incidents = len(df)
533
+ # else:
534
+ # total_incidents = len(df[
535
+ # (df['Age_Group_Drv1'] == selected_age) |
536
+ # (df['Age_Group_Drv2'] == selected_age)
537
+ # ])
538
+
539
+ with desc_col:
540
+
541
+ st.markdown("""
542
+ # Severity of Violations Across Age Groups
543
+
544
+ This section provides an interactive visualization of **crash severities** linked to specific violation types, segmented by driver age groups. It enables a comprehensive analysis of how **age influences crash severity and violation trends**. The visualization is linked to an **interactive pie chart** that updates when a specific bar is selected, displaying the detailed distribution of the selected violation type based on the selected age group.
545
+
546
+ ---
547
+
548
+ ## **Key Features**
549
+
550
+ ### 1. **Age Group Analysis**
551
+ - Select specific age groups (e.g., "16-25", "65+") or analyze all ages to explore correlations between:
552
+ - Age
553
+ - Violation type
554
+ - Crash severity
555
+ - Understand how different age groups are involved in various types of violations.
556
+
557
+ ### 2. **Violation Breakdown**
558
+ - Examine the most frequent violations contributing to traffic accidents for each age group.
559
+ - View detailed statistics showing the distribution of violation types.
560
+
561
+ ### 3. **Understanding Severity Level**
562
+ - Identify the proportion of severity levels for a specific violation type based on different age groups.
563
+ - Investigate detailed severity patterns for each violation type across age groups.
564
+
565
+ ---
566
+
567
+ ## **Insights**
568
+
569
+ - **Identifies High-Risk Behaviors:**
570
+ - Highlights risky behaviors such as reckless driving in younger drivers or impaired driving in older groups.
571
+
572
+ - **Highlights Severity Associations:**
573
+ - Shows which violations are associated with more severe outcomes, aiding targeted safety interventions and public awareness campaigns.
574
+
575
+ - **Supports Data-Driven Decision Making:**
576
+ - Provides insights for designing **age-specific traffic safety programs**.
577
+
578
+ ---
579
+ """)
580
+
581
+ with tab3:
582
+ # Dropdown for category selection
583
+ categories = [
584
+ 'Collisionmanner',
585
+ 'Lightcondition',
586
+ 'Weather',
587
+ 'SurfaceCondition',
588
+ 'AlcoholUse_Drv1',
589
+ 'Gender_Drv1',
590
+ ]
591
+ selected_category = st.selectbox("Select Category:", categories)
592
+
593
+ # Dropdown for year selection
594
+ years = ['All Years'] + sorted(df['Year'].dropna().unique().astype(int).tolist())
595
+ selected_year = st.selectbox("Select Year:", years)
596
+
597
+ chart_col, desc_col = st.columns([7, 3])
598
+
599
+ with chart_col:
600
+ distribution_chart = create_category_distribution_chart(df, selected_category, selected_year)
601
+ distribution_chart.update_layout(
602
+ height=800,
603
+ width=None,
604
+ margin=dict(l=50, r=50, t=50, b=50)
605
+ )
606
+ st.plotly_chart(distribution_chart, use_container_width=True)
607
+
608
+ with desc_col:
609
+ st.markdown(f"""
610
+ ## Distribution of Incidents by {selected_category}
611
+ 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).
612
+
613
+ **Key Features:**
614
+ * Interactive Filters: Select a category and filter by year to analyze trends over time.
615
+ * Insightful Tooltips: Hover over each segment to view the exact count and percentage of incidents for a given severity level.
616
+ * Comparative Analysis: Quickly identify how different conditions or behaviors correlate with injury severity.
617
+
618
+ This chart provides actionable insights into factors contributing to traffic incidents and their outcomes, helping stakeholders target interventions and improve road safety.
619
+ """)
620
+
621
+ with tab4:
622
+ # Dropdown for Unit Type selection
623
+ unit_type_pairs = set()
624
+ for _, row in df[['Unittype_One', 'Unittype_Two']].dropna().iterrows():
625
+ if row['Unittype_One'] != 'Driverless' or row['Unittype_Two'] != 'Driverless':
626
+ pair = ' vs '.join(sorted([row['Unittype_One'], row['Unittype_Two']]))
627
+ unit_type_pairs.add(pair)
628
+ unit_type_pairs = sorted(list(unit_type_pairs))
629
+ unit_type = st.selectbox("Select Unit Type Pair", options=['Total'] + unit_type_pairs)
630
+
631
+ chart_col, desc_col = st.columns([7, 3])
632
+
633
+ with chart_col:
634
+ injuries_fatalities_chart = create_injuries_fatalities_chart(df, unit_type)
635
+ injuries_fatalities_chart = injuries_fatalities_chart.properties(
636
+ height=800
637
+ )
638
+ st.altair_chart(injuries_fatalities_chart, use_container_width=True)
639
+
640
+ with desc_col:
641
+ st.markdown("""
642
+ ## Injuries and Fatalities Trends
643
+
644
+ 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.
645
+
646
+ **Key Features:**
647
+ * **Injuries Trend** (Blue Line)
648
+ - Tracks monthly injury counts
649
+ - Shows seasonal variations
650
+ - Identifies peak incident periods
651
+
652
+ * **Fatalities Trend** (Red Line)
653
+ - Monitors monthly fatality counts
654
+ - Generally lower than injuries
655
+ - Highlights critical safety concerns
656
+
657
+ * **Interactive Selection**
658
+ - Filter by specific unit type pairs
659
+ - Compare different vehicle combinations
660
+ - View overall trends across all types
661
+
662
+ **Applications:**
663
+ - Identify high-risk months
664
+ - Guide seasonal safety measures
665
+ - Inform emergency response planning
666
+ - Support targeted intervention strategies
667
+
668
+ This visualization aids stakeholders in developing effective safety measures and resource allocation strategies throughout the year.
669
+ """)
670
+
671
+ with tab5:
672
+ years = sorted(df['Year'].unique())
673
+ selected_year = st.selectbox('Select Year:', years)
674
+
675
+ # Create two columns for visualization and description
676
+ viz_col, desc_col = st.columns([6, 4])
677
+
678
+ with viz_col:
679
+ # First add bar chart
680
+ st.subheader("Severity-Location Analysis")
681
+ bar_fig = create_map_bar_chart(df, selected_year)
682
+
683
+ # Capture click events with bar chart
684
+ clicked_points = plotly_events(
685
+ bar_fig,
686
+ click_event=True,
687
+ override_height=300,
688
+ override_width="100%"
689
+ )
690
+
691
+ if clicked_points:
692
+ selected_severity = clicked_points[0]['x']
693
+ st.session_state["selected_severity"] = selected_severity
694
+
695
+ # Show currently selected severity
696
+ st.write(f"Selected Severity: {st.session_state['selected_severity'] if st.session_state['selected_severity'] else 'All'}")
697
+
698
+ # Add map below bar chart
699
+ st.subheader("Accident Locations")
700
+ map_placeholder = st.empty()
701
+ with map_placeholder:
702
+ m = create_map(df, selected_year, st.session_state["selected_severity"])
703
+ map_data = st_folium(
704
+ m,
705
+ width=None,
706
+ height=600, # Reduced height since it's now below bar chart
707
+ key=f"map_{selected_year}_{st.session_state['selected_severity']}",
708
+ returned_objects=["null_drawing"]
709
+ )
710
+
711
+ with desc_col:
712
+ st.markdown("""
713
+ # Exploring Traffic Accident Severity and Location
714
+ The two linked graphs show an interactive platform for exploring traffic accident data, featuring a **bar chart** and a **dynamic map**.
715
+ - The **bar chart** displays the distribution of accidents by severity.
716
+ - The **map** combines marker clustering and heatmaps to highlight accident locations.
717
+ - Users can filter data by year and severity to explore patterns.
718
+ ---
719
+ ## **Key Features**
720
+ - **Interactive Bar Chart:**
721
+ Displays accident counts by severity, updating the map based on selected severity.
722
+ - **Map with Dual Layers:**
723
+ Includes marker clustering for individual accidents and a heatmap to visualize accident density.
724
+ - **Year-Based Filtering:**
725
+ Allows users to filter data by year and severity for focused analysis.
726
+ - **Seamless Integration:**
727
+ Combines Streamlit and Folium, with Plotly events linking the visualizations.
728
+ ---
729
+ ## **Design**
730
+ - **Bar Chart:**
731
+ - Uses a calm blue color for clarity.
732
+ - **Map:**
733
+ - Uses **CartoDB tiles** with red markers and heatmaps for visibility.
734
+ ---
735
+ ## **Insights**
736
+ - **Severity Patterns:**
737
+ The bar chart reveals accident trends across severity levels.
738
+ - **Spatial Trends:**
739
+ The map identifies high-risk accident hotspots.
740
+ - **Yearly and Severity Insights:**
741
+ Filters help uncover temporal and severity-related patterns, aiding traffic safety analysis.
742
+ """)
743
+ st.markdown("---")
744
+
745
+ # Add conclusion section
746
+ st.markdown("# Summary and Conclusion")
747
+
748
+ st.markdown("""
749
+
750
+ This project analyzed traffic accident data for Tempe, Arizona, using interactive visualizations to uncover critical trends and patterns. Key visualizations included crash trends over time, severity analysis by age and violations, injury and fatality trends, and the distribution of incidents across factors like weather and collision manner.
751
+
752
+ A highlight was the integration of linked visualizations, such as bar charts and dynamic maps, enabling users to explore data interactively. This linkage allowed for seamless filtering and focused analysis of severity and location patterns, making it easier to identify high-risk areas and contributing factors.
753
+
754
+ These insights are invaluable for city planners, traffic authorities, and safety advocates, helping them design targeted interventions, allocate resources effectively, and improve overall road safety in Tempe.
755
+ """)
756
+
757
+
758
+
759
+ if __name__ == "__main__":
760
+ main()