File size: 2,545 Bytes
c2601b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Importing necessary libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Setting up seaborn
sns.set(color_codes=True)

# Function to load and preprocess data
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

# Function for plotting hourly accidents distribution
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}")

# Function for plotting weather conditions
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}")

# Main script
def main():
    # Load and preprocess data
    df = load_and_preprocess_data('US_Accidents_March23.csv')

    # Check if DataFrame is loaded correctly
    if df is not None and not df.empty:
        # Plotting functions
        plot_hourly_accidents(df)
        plot_weather_conditions(df)
    else:
        print("Data loading failed or the DataFrame is empty.")

# Run the main script
main()