|
|
|
import pandas as pd |
|
import seaborn as sns |
|
import matplotlib.pyplot as plt |
|
|
|
|
|
sns.set(color_codes=True) |
|
|
|
|
|
def load_and_preprocess_data(filepath): |
|
try: |
|
df = pd.read_csv(filepath) |
|
df['Start_Time'] = pd.to_datetime(df['Start_Time'], format='mixed', errors='coerce') |
|
return df |
|
except Exception as e: |
|
print(f"An error occurred while loading data: {e}") |
|
return None |
|
|
|
|
|
def plot_hourly_accidents(df): |
|
try: |
|
fig, axes = plt.subplots(4, 2, figsize=(18, 10)) |
|
plt.subplots_adjust(hspace=0.5) |
|
blue_palette = sns.light_palette("blue", n_colors=8, reverse=True) |
|
|
|
for i in range(8): |
|
ax = axes[i//2, i%2] |
|
if i == 0: |
|
sns.histplot(df['Start_Time'].dt.hour, bins=24, ax=ax, color=blue_palette[i]) |
|
ax.set_title("Overall Hourly Accident Distribution") |
|
else: |
|
day_data = df[df['Start_Time'].dt.dayofweek == i-1] |
|
sns.histplot(day_data['Start_Time'].dt.hour, bins=24, ax=ax, color=blue_palette[i]) |
|
ax.set_title(f"Hourly Distribution: {day_data['Start_Time'].dt.day_name().iloc[0]}") |
|
ax.set_xlabel("Hour") |
|
ax.set_ylabel("Accidents") |
|
|
|
plt.tight_layout() |
|
plt.show() |
|
except Exception as e: |
|
print(f"An error occurred while plotting hourly accidents: {e}") |
|
|
|
|
|
def plot_weather_conditions(df): |
|
try: |
|
weather = df['Weather_Condition'].value_counts().head(15) |
|
plt.figure(figsize=(30, 10)) |
|
sns.barplot(x=weather.index, y=weather.values, palette="Reds_r") |
|
plt.xticks(rotation=45, fontsize=15) |
|
plt.yticks(fontsize=15) |
|
plt.xlabel("Weather Condition", fontsize=20) |
|
plt.ylabel("Count", fontsize=20) |
|
plt.title("Weather Condition vs Accidents", fontsize=30) |
|
plt.show() |
|
except Exception as e: |
|
print(f"An error occurred while plotting weather conditions: {e}") |
|
|
|
|
|
def main(): |
|
|
|
df = load_and_preprocess_data('US_Accidents_March23.csv') |
|
|
|
|
|
if df is not None and not df.empty: |
|
|
|
plot_hourly_accidents(df) |
|
plot_weather_conditions(df) |
|
else: |
|
print("Data loading failed or the DataFrame is empty.") |
|
|
|
|
|
main() |
|
|