|
import streamlit as st |
|
import pandas as pd |
|
import plotly.express as px |
|
import altair as alt |
|
import folium |
|
from streamlit_plotly_events import plotly_events |
|
from folium.plugins import HeatMap, MarkerCluster |
|
from streamlit_folium import st_folium |
|
|
|
|
|
severity_colors = { |
|
"No Injury": "#1f77b4", |
|
"Possible Injury": "#aec7e8", |
|
"Non Incapacitating Injury": "#ff7f0e", |
|
"Incapacitating Injury": "#ffbb78", |
|
"Suspected Minor Injury": "#2ca02c", |
|
"Suspected Serious Injury": "#98df8a", |
|
"Fatal": "#d62728", |
|
} |
|
|
|
@st.cache_data |
|
def load_and_preprocess_data(file_path): |
|
|
|
df = pd.read_csv(file_path) |
|
|
|
|
|
df = df.drop(['X', 'Y'], axis=1) |
|
df.dropna(subset=['Incidentid', 'DateTime', 'Year', 'Latitude', 'Longitude'], inplace=True) |
|
|
|
|
|
df['Year'] = df['Year'].astype(int) |
|
|
|
|
|
numeric = ['Age_Drv1', 'Age_Drv2'] |
|
for col in numeric: |
|
df[col].fillna(df[col].median(), inplace=True) |
|
|
|
categorical = ['Gender_Drv1', 'Violation1_Drv1', 'AlcoholUse_Drv1', 'DrugUse_Drv1', |
|
'Gender_Drv2', 'Violation1_Drv2', 'AlcoholUse_Drv2', 'DrugUse_Drv2', |
|
'Unittype_Two', 'Traveldirection_Two', 'Unitaction_Two', 'CrossStreet'] |
|
for col in categorical: |
|
df[col].fillna('Unknown', inplace=True) |
|
|
|
|
|
df = df[ |
|
(df['Age_Drv1'] <= 90) & |
|
(df['Age_Drv2'] <= 90) & |
|
(df['Age_Drv1'] >= 16) & |
|
(df['Age_Drv2'] >= 16) |
|
] |
|
|
|
|
|
bins = [15, 25, 35, 45, 55, 65, 90] |
|
labels = ['16-25', '26-35', '36-45', '46-55', '56-65', '65+'] |
|
|
|
df['Age_Group_Drv1'] = pd.cut(df['Age_Drv1'], bins=bins, labels=labels) |
|
df['Age_Group_Drv2'] = pd.cut(df['Age_Drv2'], bins=bins, labels=labels) |
|
|
|
return df |
|
|
|
def create_severity_violation_chart(df, age_group=None): |
|
|
|
if age_group != 'All Ages': |
|
df = df[(df['Age_Group_Drv1'] == age_group) | (df['Age_Group_Drv2'] == age_group)] |
|
|
|
|
|
violations_1 = df.groupby(['Violation1_Drv1', 'Injuryseverity']).size().reset_index(name='count') |
|
violations_2 = df.groupby(['Violation1_Drv2', 'Injuryseverity']).size().reset_index(name='count') |
|
|
|
violations_1.columns = ['Violation', 'Severity', 'count'] |
|
violations_2.columns = ['Violation', 'Severity', 'count'] |
|
|
|
violations = pd.concat([violations_1, violations_2]) |
|
violations = violations.groupby(['Violation', 'Severity'])['count'].sum().reset_index() |
|
|
|
|
|
fig = px.bar( |
|
violations, |
|
x='Violation', |
|
y='count', |
|
color='Severity', |
|
title=f'Crash Severity Distribution by Violation Type - {age_group}', |
|
labels={'count': 'Number of Incidents', 'Violation': 'Violation Type'}, |
|
height=600, |
|
color_discrete_map=severity_colors, |
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fig.update_layout( |
|
xaxis_tickangle=-45, |
|
legend_title='Severity Level', |
|
barmode='stack', |
|
margin=dict(t=50, b=150), |
|
xaxis=dict(automargin=True) |
|
) |
|
|
|
|
|
return fig, violations |
|
|
|
def get_top_violations(df, age_group): |
|
|
|
if age_group == 'All Ages': |
|
total_incidents = len(df) |
|
|
|
violations = pd.concat([ |
|
df['Violation1_Drv1'].value_counts(), |
|
df['Violation1_Drv2'].value_counts() |
|
]).groupby(level=0).sum() |
|
else: |
|
|
|
filtered_df = df[ |
|
(df['Age_Group_Drv1'] == age_group) | |
|
(df['Age_Group_Drv2'] == age_group) |
|
] |
|
total_incidents = len(filtered_df) |
|
|
|
violations = pd.concat([ |
|
filtered_df['Violation1_Drv1'].value_counts(), |
|
filtered_df['Violation1_Drv2'].value_counts() |
|
]).groupby(level=0).sum() |
|
|
|
|
|
violations_df = violations.reset_index() |
|
violations_df.columns = ['Violation Type', 'Count'] |
|
|
|
|
|
violations_df = violations_df.sort_values('Count', ascending=False) |
|
|
|
|
|
violations_df['Percentage'] = (violations_df['Count'] / total_incidents * 100).round(2) |
|
violations_df['Percentage'] = violations_df['Percentage'].map('{:.2f}%'.format) |
|
|
|
return violations_df.head() |
|
|
|
@st.cache_data |
|
def create_interactive_pie_chart(violations, selected_violation, selected_age): |
|
|
|
filtered_data = violations[violations['Violation'] == selected_violation] |
|
|
|
|
|
fig = px.pie( |
|
filtered_data, |
|
names='Severity', |
|
values='count', |
|
|
|
title=f'Severity Level Distribution for Violation: {selected_violation} - {selected_age}', |
|
height=600, |
|
color_discrete_map=severity_colors |
|
) |
|
|
|
return fig |
|
|
|
def create_map_bar_chart(df, selected_year): |
|
|
|
filtered_df = df[df['Year'] == selected_year] |
|
severity_count = filtered_df['Injuryseverity'].value_counts().reset_index() |
|
severity_count.columns = ['Injuryseverity', 'Count'] |
|
|
|
fig = px.bar( |
|
severity_count, |
|
x='Injuryseverity', |
|
y='Count', |
|
title="Accidents by Severity", |
|
labels={'Injuryseverity': 'Severity', 'Count': 'Number of Accidents'} |
|
) |
|
fig.update_traces(marker_color='blue') |
|
fig.update_layout( |
|
clickmode='event+select', |
|
xaxis_tickangle=45, |
|
margin=dict(t=50, b=150), |
|
) |
|
return fig |
|
|
|
|
|
@st.cache_data |
|
def create_map(df, selected_year, selected_severity=None): |
|
|
|
filtered_df = df[df['Year'] == selected_year] |
|
|
|
|
|
if selected_severity: |
|
filtered_df = filtered_df[filtered_df['Injuryseverity'] == selected_severity] |
|
|
|
|
|
filtered_df = filtered_df.dropna(subset=['Latitude', 'Longitude']) |
|
|
|
|
|
m = folium.Map( |
|
location=[33.4255, -111.9400], |
|
zoom_start=12, |
|
control_scale=True, |
|
tiles='CartoDB positron' |
|
) |
|
|
|
|
|
marker_cluster = MarkerCluster(name="Accident Locations").add_to(m) |
|
|
|
|
|
for _, row in filtered_df.iterrows(): |
|
folium.Marker( |
|
location=[row['Latitude'], row['Longitude']], |
|
popup=f"Accident at {row['Longitude']}, {row['Latitude']}<br>Date: {row['DateTime']}<br>Severity: {row['Injuryseverity']}", |
|
icon=folium.Icon(color='red') |
|
).add_to(marker_cluster) |
|
|
|
|
|
heat_data = filtered_df[['Latitude', 'Longitude']].values.tolist() |
|
HeatMap(heat_data, radius=15, max_zoom=13, min_opacity=0.3, name="Heat Map").add_to(m) |
|
|
|
folium.LayerControl().add_to(m) |
|
return m |
|
|
|
def create_injuries_fatalities_chart(crash_data, unit_type): |
|
|
|
|
|
|
|
|
|
|
|
crash_data = crash_data[['DateTime', 'Totalinjuries', 'Totalfatalities', 'Unittype_One', 'Unittype_Two']].dropna() |
|
|
|
|
|
crash_data['DateTime'] = pd.to_datetime(crash_data['DateTime'], errors='coerce') |
|
crash_data['Month'] = crash_data['DateTime'].dt.month_name() |
|
|
|
|
|
month_order = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] |
|
crash_data['Month'] = pd.Categorical(crash_data['Month'], categories=month_order, ordered=True) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if unit_type == 'Total': |
|
filtered_data = crash_data |
|
else: |
|
unit_one, unit_two = unit_type.split(' vs ') |
|
filtered_data = crash_data[((crash_data['Unittype_One'] == unit_one) & (crash_data['Unittype_Two'] == unit_two)) | |
|
((crash_data['Unittype_One'] == unit_two) & (crash_data['Unittype_Two'] == unit_one))] |
|
|
|
|
|
monthly_sum = filtered_data.groupby('Month').agg({'Totalinjuries': 'sum', 'Totalfatalities': 'sum'}).reset_index() |
|
|
|
|
|
injuries = monthly_sum[['Month', 'Totalinjuries']].rename(columns={'Totalinjuries': 'Value'}) |
|
injuries['Measure'] = 'Total Injuries' |
|
|
|
fatalities = monthly_sum[['Month', 'Totalfatalities']].rename(columns={'Totalfatalities': 'Value'}) |
|
fatalities['Measure'] = 'Total Fatalities' |
|
|
|
combined_data = pd.concat([injuries, fatalities]) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
line_chart = alt.Chart(combined_data).mark_line(point=True).encode( |
|
x=alt.X('Month:N', sort=month_order, title='Month'), |
|
y=alt.Y('Value:Q', title='Total Injuries & Fatalities'), |
|
color=alt.Color('Measure:N', title='', scale=alt.Scale(domain=['Total Injuries', 'Total Fatalities'], range=['blue', 'red'])), |
|
tooltip=['Month', 'Measure:N', 'Value:Q'] |
|
).properties( |
|
title=f'Total Injuries and Fatalities by Month for Unit Type Pair: {unit_type}', |
|
width=600, |
|
height=400 |
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return line_chart |
|
|
|
def create_crash_trend_chart(df, weather=None): |
|
if weather and weather != 'All Conditions': |
|
df = df[df['Weather'] == weather] |
|
|
|
|
|
trend_data = df.groupby('Year')['Incidentid'].nunique().reset_index() |
|
trend_data.columns = ['Year', 'Crash Count'] |
|
|
|
|
|
fig = px.line( |
|
trend_data, |
|
x='Year', |
|
y='Crash Count', |
|
title=f'Crash Trend Over Time ({weather})', |
|
labels={'Year': 'Year', 'Crash Count': 'Number of Unique Crashes'}, |
|
markers=True, |
|
height=600 |
|
) |
|
|
|
fig.update_traces(line=dict(width=2), marker=dict(size=8)) |
|
fig.update_layout(legend_title_text='Trend') |
|
|
|
return fig |
|
|
|
def create_category_distribution_chart(df, selected_category, selected_year): |
|
|
|
if selected_year != 'All Years': |
|
df = df[df['Year'] == int(selected_year)] |
|
|
|
|
|
grouped_data = df.groupby([selected_category, 'Injuryseverity']).size().reset_index(name='Count') |
|
|
|
|
|
total_counts = grouped_data.groupby(selected_category)['Count'].transform('sum') |
|
grouped_data['Percentage'] = (grouped_data['Count'] / total_counts * 100).round(2) |
|
|
|
|
|
fig = px.bar( |
|
grouped_data, |
|
x=selected_category, |
|
y='Count', |
|
color='Injuryseverity', |
|
text='Percentage', |
|
title=f'Distribution of Incidents by {selected_category} ({selected_year})', |
|
labels={'Count': 'Number of Incidents', selected_category: 'Category'}, |
|
height=600, |
|
) |
|
|
|
|
|
fig.update_traces(texttemplate='%{text}%', textposition='inside') |
|
fig.update_layout( |
|
barmode='stack', |
|
xaxis_tickangle=-45, |
|
legend_title='Injury Severity', |
|
margin=dict(t=50, b=150, l=50, r=50), |
|
) |
|
|
|
return fig |
|
|
|
def main(): |
|
st.set_page_config(page_title="Terrific Tempe Traffic", layout="wide") |
|
|
|
st.markdown(""" |
|
<style> |
|
.reportview-container { |
|
font-size: 20px; |
|
} |
|
h1, h2, h3, h4, h5, h6 { |
|
font-size: 150%; |
|
} |
|
p { |
|
font-size: 125%; |
|
} |
|
</style> |
|
""", unsafe_allow_html=True) |
|
|
|
|
|
st.markdown(""" |
|
<style> |
|
.title { |
|
text-align: center; |
|
padding: 25px; |
|
} |
|
</style> |
|
""", unsafe_allow_html=True) |
|
|
|
st.markdown("<div class='title'><h1> Accident Analysis for City of Tempe, Arizona </h1></div>", unsafe_allow_html=True) |
|
|
|
st.markdown(""" |
|
# Introduction to the Traffic Accident Dataset |
|
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. |
|
|
|
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. |
|
""") |
|
|
|
|
|
|
|
|
|
df = load_and_preprocess_data('1.08_Crash_Data_Report_(detail).csv') |
|
|
|
if 'Weather' not in df.columns: |
|
df['Weather'] = 'Unknown' |
|
|
|
if 'selected_violation' not in st.session_state: |
|
st.session_state['selected_violation'] = None |
|
|
|
if "selected_severity" not in st.session_state: |
|
st.session_state["selected_severity"] = None |
|
|
|
|
|
|
|
tab1, tab2, tab3, tab4, tab5 = st.tabs([ |
|
"Crash Trend", |
|
"Violation-Severity Analysis", |
|
"Distribution by Category", |
|
"Crash Injuries/Fatalities", |
|
"Severity-Location Analysis" |
|
]) |
|
|
|
with tab1: |
|
|
|
weather = ['All Conditions'] + sorted(df['Weather'].unique()) |
|
selected_weather = st.selectbox('Select Weather Condition:', weather) |
|
|
|
trend_col, desc_col = st.columns([7, 3]) |
|
|
|
with trend_col: |
|
trend_fig = create_crash_trend_chart(df, selected_weather) |
|
trend_fig.update_layout( |
|
height=800, |
|
width=None, |
|
margin=dict(l=50, r=50, t=50, b=50) |
|
) |
|
st.plotly_chart(trend_fig, use_container_width=True) |
|
|
|
|
|
|
|
with desc_col: |
|
st.markdown(""" |
|
## **Crash Trend Over Time** |
|
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. |
|
|
|
**Key Features:** |
|
* **Time Trend Analysis**: Displays the total number of unique crashes for each year, showing long-term patterns. |
|
* **Weather Filter**: Users can filter the data by weather conditions (e.g., "Rainy", "Sunny") to analyze how weather impacts crash trends. |
|
* **Interactive Tooltips**: Hovering over data points reveals the exact crash count for each year, providing detailed insights. |
|
|
|
**Color Scheme and Design:** |
|
* **Line and Markers**: A smooth line connects data points, with prominent markers for each year to highlight trends clearly. |
|
* **Dynamic Title**: The chart updates its title to reflect the selected weather condition or "All Conditions" for the overall trend. |
|
|
|
**Insights:** |
|
|
|
This chart helps uncover: |
|
* Annual fluctuations in crash incidents. |
|
* Correlations between weather conditions and crash frequencies. |
|
* Historical patterns that can guide future safety measures and urban planning decisions |
|
""") |
|
|
|
with tab2: |
|
|
|
age_groups = ['All Ages', '16-25', '26-35', '36-45', '46-55', '56-65', '65+'] |
|
selected_age = st.selectbox('Select Age Group:', age_groups) |
|
|
|
trend_col, desc_col = st.columns([6, 4]) |
|
|
|
with trend_col: |
|
|
|
fig, violations = create_severity_violation_chart(df, selected_age) |
|
|
|
|
|
chart_event = st.plotly_chart( |
|
fig, |
|
use_container_width=True, |
|
key="violation_chart", |
|
on_select="rerun" |
|
) |
|
|
|
|
|
if chart_event and chart_event.selection and chart_event.selection.points: |
|
|
|
selected_violation = chart_event.selection.points[0]['x'] |
|
|
|
pie_chart = create_interactive_pie_chart(violations, selected_violation, selected_age) |
|
st.plotly_chart(pie_chart, use_container_width=True) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with desc_col: |
|
|
|
st.markdown(""" |
|
# Severity of Violations Across Age Groups |
|
|
|
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. |
|
|
|
--- |
|
|
|
## **Key Features** |
|
|
|
### 1. **Age Group Analysis** |
|
- Select specific age groups (e.g., "16-25", "65+") or analyze all ages to explore correlations between: |
|
- Age |
|
- Violation type |
|
- Crash severity |
|
- Understand how different age groups are involved in various types of violations. |
|
|
|
### 2. **Violation Breakdown** |
|
- Examine the most frequent violations contributing to traffic accidents for each age group. |
|
- View detailed statistics showing the distribution of violation types. |
|
|
|
### 3. **Understanding Severity Level** |
|
- Identify the proportion of severity levels for a specific violation type based on different age groups. |
|
- Investigate detailed severity patterns for each violation type across age groups. |
|
|
|
--- |
|
|
|
## **Insights** |
|
|
|
- **Identifies High-Risk Behaviors:** |
|
- Highlights risky behaviors such as reckless driving in younger drivers or impaired driving in older groups. |
|
|
|
- **Highlights Severity Associations:** |
|
- Shows which violations are associated with more severe outcomes, aiding targeted safety interventions and public awareness campaigns. |
|
|
|
- **Supports Data-Driven Decision Making:** |
|
- Provides insights for designing **age-specific traffic safety programs**. |
|
|
|
--- |
|
""") |
|
|
|
with tab3: |
|
|
|
categories = [ |
|
'Collisionmanner', |
|
'Lightcondition', |
|
'Weather', |
|
'SurfaceCondition', |
|
'AlcoholUse_Drv1', |
|
'Gender_Drv1', |
|
] |
|
selected_category = st.selectbox("Select Category:", categories) |
|
|
|
|
|
years = ['All Years'] + sorted(df['Year'].dropna().unique().astype(int).tolist()) |
|
selected_year = st.selectbox("Select Year:", years) |
|
|
|
chart_col, desc_col = st.columns([7, 3]) |
|
|
|
with chart_col: |
|
distribution_chart = create_category_distribution_chart(df, selected_category, selected_year) |
|
distribution_chart.update_layout( |
|
height=800, |
|
width=None, |
|
margin=dict(l=50, r=50, t=50, b=50) |
|
) |
|
st.plotly_chart(distribution_chart, use_container_width=True) |
|
|
|
with desc_col: |
|
st.markdown(f""" |
|
## Distribution of Incidents by {selected_category} |
|
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). |
|
|
|
**Key Features:** |
|
* Interactive Filters: Select a category and filter by year to analyze trends over time. |
|
* Insightful Tooltips: Hover over each segment to view the exact count and percentage of incidents for a given severity level. |
|
* Comparative Analysis: Quickly identify how different conditions or behaviors correlate with injury severity. |
|
|
|
This chart provides actionable insights into factors contributing to traffic incidents and their outcomes, helping stakeholders target interventions and improve road safety. |
|
""") |
|
|
|
with tab4: |
|
|
|
unit_type_pairs = set() |
|
for _, row in df[['Unittype_One', 'Unittype_Two']].dropna().iterrows(): |
|
if row['Unittype_One'] != 'Driverless' or row['Unittype_Two'] != 'Driverless': |
|
pair = ' vs '.join(sorted([row['Unittype_One'], row['Unittype_Two']])) |
|
unit_type_pairs.add(pair) |
|
unit_type_pairs = sorted(list(unit_type_pairs)) |
|
unit_type = st.selectbox("Select Unit Type Pair", options=['Total'] + unit_type_pairs) |
|
|
|
chart_col, desc_col = st.columns([7, 3]) |
|
|
|
with chart_col: |
|
injuries_fatalities_chart = create_injuries_fatalities_chart(df, unit_type) |
|
injuries_fatalities_chart = injuries_fatalities_chart.properties( |
|
height=800 |
|
) |
|
st.altair_chart(injuries_fatalities_chart, use_container_width=True) |
|
|
|
with desc_col: |
|
st.markdown(""" |
|
## Injuries and Fatalities Trends |
|
|
|
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. |
|
|
|
**Key Features:** |
|
* **Injuries Trend** (Blue Line) |
|
- Tracks monthly injury counts |
|
- Shows seasonal variations |
|
- Identifies peak incident periods |
|
|
|
* **Fatalities Trend** (Red Line) |
|
- Monitors monthly fatality counts |
|
- Generally lower than injuries |
|
- Highlights critical safety concerns |
|
|
|
* **Interactive Selection** |
|
- Filter by specific unit type pairs |
|
- Compare different vehicle combinations |
|
- View overall trends across all types |
|
|
|
**Applications:** |
|
- Identify high-risk months |
|
- Guide seasonal safety measures |
|
- Inform emergency response planning |
|
- Support targeted intervention strategies |
|
|
|
This visualization aids stakeholders in developing effective safety measures and resource allocation strategies throughout the year. |
|
""") |
|
|
|
with tab5: |
|
years = sorted(df['Year'].unique()) |
|
selected_year = st.selectbox('Select Year:', years) |
|
|
|
|
|
viz_col, desc_col = st.columns([6, 4]) |
|
|
|
with viz_col: |
|
|
|
st.subheader("Severity-Location Analysis") |
|
bar_fig = create_map_bar_chart(df, selected_year) |
|
|
|
|
|
clicked_points = plotly_events( |
|
bar_fig, |
|
click_event=True, |
|
override_height=300, |
|
override_width="100%" |
|
) |
|
|
|
if clicked_points: |
|
selected_severity = clicked_points[0]['x'] |
|
st.session_state["selected_severity"] = selected_severity |
|
|
|
|
|
st.write(f"Selected Severity: {st.session_state['selected_severity'] if st.session_state['selected_severity'] else 'All'}") |
|
|
|
|
|
st.subheader("Accident Locations") |
|
map_placeholder = st.empty() |
|
with map_placeholder: |
|
m = create_map(df, selected_year, st.session_state["selected_severity"]) |
|
map_data = st_folium( |
|
m, |
|
width=None, |
|
height=600, |
|
key=f"map_{selected_year}_{st.session_state['selected_severity']}", |
|
returned_objects=["null_drawing"] |
|
) |
|
|
|
with desc_col: |
|
st.markdown(""" |
|
# Exploring Traffic Accident Severity and Location |
|
The two linked graphs show an interactive platform for exploring traffic accident data, featuring a **bar chart** and a **dynamic map**. |
|
- The **bar chart** displays the distribution of accidents by severity. |
|
- The **map** combines marker clustering and heatmaps to highlight accident locations. |
|
- Users can filter data by year and severity to explore patterns. |
|
--- |
|
## **Key Features** |
|
- **Interactive Bar Chart:** |
|
Displays accident counts by severity, updating the map based on selected severity. |
|
- **Map with Dual Layers:** |
|
Includes marker clustering for individual accidents and a heatmap to visualize accident density. |
|
- **Year-Based Filtering:** |
|
Allows users to filter data by year and severity for focused analysis. |
|
- **Seamless Integration:** |
|
Combines Streamlit and Folium, with Plotly events linking the visualizations. |
|
--- |
|
## **Design** |
|
- **Bar Chart:** |
|
- Uses a calm blue color for clarity. |
|
- **Map:** |
|
- Uses **CartoDB tiles** with red markers and heatmaps for visibility. |
|
--- |
|
## **Insights** |
|
- **Severity Patterns:** |
|
The bar chart reveals accident trends across severity levels. |
|
- **Spatial Trends:** |
|
The map identifies high-risk accident hotspots. |
|
- **Yearly and Severity Insights:** |
|
Filters help uncover temporal and severity-related patterns, aiding traffic safety analysis. |
|
""") |
|
st.markdown("---") |
|
|
|
|
|
st.markdown("# Summary and Conclusion") |
|
|
|
st.markdown(""" |
|
|
|
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. |
|
|
|
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. |
|
|
|
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. |
|
""") |
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
main() |