NoCommentsElder commited on
Commit
c2601b9
1 Parent(s): 2e1ea6d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -0
app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries
2
+ import pandas as pd
3
+ import seaborn as sns
4
+ import matplotlib.pyplot as plt
5
+
6
+ # Setting up seaborn
7
+ sns.set(color_codes=True)
8
+
9
+ # Function to load and preprocess data
10
+ def load_and_preprocess_data(filepath):
11
+ try:
12
+ df = pd.read_csv(filepath)
13
+ df['Start_Time'] = pd.to_datetime(df['Start_Time'], format='mixed', errors='coerce')
14
+ return df
15
+ except Exception as e:
16
+ print(f"An error occurred while loading data: {e}")
17
+ return None
18
+
19
+ # Function for plotting hourly accidents distribution
20
+ def plot_hourly_accidents(df):
21
+ try:
22
+ fig, axes = plt.subplots(4, 2, figsize=(18, 10))
23
+ plt.subplots_adjust(hspace=0.5)
24
+ blue_palette = sns.light_palette("blue", n_colors=8, reverse=True)
25
+
26
+ for i in range(8):
27
+ ax = axes[i//2, i%2]
28
+ if i == 0:
29
+ sns.histplot(df['Start_Time'].dt.hour, bins=24, ax=ax, color=blue_palette[i])
30
+ ax.set_title("Overall Hourly Accident Distribution")
31
+ else:
32
+ day_data = df[df['Start_Time'].dt.dayofweek == i-1]
33
+ sns.histplot(day_data['Start_Time'].dt.hour, bins=24, ax=ax, color=blue_palette[i])
34
+ ax.set_title(f"Hourly Distribution: {day_data['Start_Time'].dt.day_name().iloc[0]}")
35
+ ax.set_xlabel("Hour")
36
+ ax.set_ylabel("Accidents")
37
+
38
+ plt.tight_layout()
39
+ plt.show()
40
+ except Exception as e:
41
+ print(f"An error occurred while plotting hourly accidents: {e}")
42
+
43
+ # Function for plotting weather conditions
44
+ def plot_weather_conditions(df):
45
+ try:
46
+ weather = df['Weather_Condition'].value_counts().head(15)
47
+ plt.figure(figsize=(30, 10))
48
+ sns.barplot(x=weather.index, y=weather.values, palette="Reds_r")
49
+ plt.xticks(rotation=45, fontsize=15)
50
+ plt.yticks(fontsize=15)
51
+ plt.xlabel("Weather Condition", fontsize=20)
52
+ plt.ylabel("Count", fontsize=20)
53
+ plt.title("Weather Condition vs Accidents", fontsize=30)
54
+ plt.show()
55
+ except Exception as e:
56
+ print(f"An error occurred while plotting weather conditions: {e}")
57
+
58
+ # Main script
59
+ def main():
60
+ # Load and preprocess data
61
+ df = load_and_preprocess_data('US_Accidents_March23.csv')
62
+
63
+ # Check if DataFrame is loaded correctly
64
+ if df is not None and not df.empty:
65
+ # Plotting functions
66
+ plot_hourly_accidents(df)
67
+ plot_weather_conditions(df)
68
+ else:
69
+ print("Data loading failed or the DataFrame is empty.")
70
+
71
+ # Run the main script
72
+ main()