import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, MonthLocator
from matplotlib.ticker import MaxNLocator
import seaborn as sns
import tkinter as tk
from tkinter import filedialog
# Set modern style
sns.set(style="whitegrid")
plt.style.use('ggplot')
# Hide Tkinter root window
tk.Tk().withdraw()
# Ask user to select a CSV file
csv_file = filedialog.askopenfilename(
title="Select CSV file",
filetypes=[("CSV files", "*.csv")]
)
if not csv_file:
print("No file selected. Exiting.")
exit()
# Load data from CSV
df = pd.read_csv(csv_file)
# Convert 'Date' column to datetime
df['Date'] = pd.to_datetime(df['Date'])
# Sort by date (if not already sorted)
df = df.sort_values('Date').reset_index(drop=True)
# --- Calculate the lag between rainfall and groundwater recharge ---
def calculate_lag(rainfall, groundwater, max_lag=30):
"""
Calculate the lag (in days) between rainfall and groundwater recharge using cross-correlation.
"""
# Remove NaN values for correlation
valid_data = pd.concat([rainfall, groundwater], axis=1).dropna()
rainfall_valid = valid_data.iloc[:, 0]
groundwater_valid = valid_data.iloc[:, 1]
# Calculate cross-correlation
correlation = np.correlate(rainfall_valid - rainfall_valid.mean(),
groundwater_valid - groundwater_valid.mean(), mode='full')
lags = np.arange(-len(rainfall_valid) + 1, len(rainfall_valid))
# Find the lag with maximum correlation
max_corr_idx = np.argmax(correlation)
lag = lags[max_corr_idx]
# Limit lag to max_lag days
if abs(lag) > max_lag:
lag = 0 # If lag is too large, assume no significant correlation
return lag
# Calculate lag (in days)
rainfall = df['Rainfall (mm)']
groundwater = df['Groundwater Level (m)']
lag_days = calculate_lag(rainfall, groundwater)
print(f"Calculated lag between rainfall and groundwater recharge: {lag_days} days")
# Shift groundwater data by the calculated lag
df['Shifted Groundwater Level (m)'] = df['Groundwater Level (m)'].shift(-lag_days) # Negative shift to align with rainfall
# Create figure and axes
fig, ax1 = plt.subplots(figsize=(14, 7))
# --- Plot Rainfall on top (above x-axis) ---
rain_bars = ax1.bar(df['Date'], df['Rainfall (mm)'], color='#2E86AB', label='Rainfall', width=0.8)
ax1.set_xlabel('Date', fontsize=14, labelpad=10)
ax1.set_ylabel('Rainfall (mm)', color='#2E86AB', fontsize=14)
ax1.tick_params(axis='y', labelcolor='#2E86AB')
# --- Plot Original and Shifted Groundwater below x-axis (in 4th quadrant) ---
ax2 = ax1.twinx()
groundwater = -df['Groundwater Level (m)']
shifted_groundwater = -df['Shifted Groundwater Level (m)']
smoothed_groundwater = groundwater.rolling(window=7, center=True).mean() # Smooth the original line
smoothed_shifted_groundwater = shifted_groundwater.rolling(window=7, center=True).mean() # Smooth the shifted line
# Plot original groundwater
ground_line, = ax2.plot(df['Date'], smoothed_groundwater, color='#28A745',
linewidth=2.5, linestyle='--', marker='o', markersize=6,
label='Groundwater Level (Original)')
# Plot shifted groundwater
shifted_ground_line, = ax2.plot(df['Date'], smoothed_shifted_groundwater, color='#FF5733',
linewidth=2.5, linestyle='-', marker='x', markersize=6,
label=f'Groundwater Level (Shifted by {lag_days} days)')
ax2.set_ylabel('Groundwater Level (m)', color='#28A745', fontsize=14)
ax2.tick_params(axis='y', labelcolor='#28A745')
# --- Formatting X-Axis with Monthly Ticks ---
ax1.xaxis.set_major_locator(MonthLocator()) # Set ticks at the start of each month
ax1.xaxis.set_major_formatter(DateFormatter("%b %Y")) # Format as "Month Year"
fig.autofmt_xdate() # Rotate and align the tick labels
# Horizontal line at y=0 for clarity
ax1.axhline(0, color='black', linewidth=1, linestyle='--', alpha=0.6)
# Title and subtitle
plt.title('Daily Rainfall (Above) and Groundwater Level (Below)\n[With Delay Effect Highlighted]',
fontsize=16, pad=20, fontweight='bold')
# Add grid manually for better control
ax1.grid(True, which='major', axis='y', linestyle='--', linewidth=0.5, alpha=0.7)
# --- Legend Setup ---
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2,
loc='upper right', fontsize=12, frameon=True, shadow=True)
# Adjust layout
fig.tight_layout()
# --- Ask where to save the plot ---
save_path = filedialog.asksaveasfilename(
title="Save Plot As",
defaultextension=".png",
filetypes=[
("PNG Image", "*.png"),
("PDF Document", "*.pdf"),
("JPEG Image", "*.jpg"),
("SVG Vector", "*.svg"),
("All Files", "*.*")
]
)
if save_path:
try:
fig.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Plot saved successfully to: {save_path}")
except Exception as e:
print(f"Error saving file: {e}")
else:
print("Save canceled.")
# Show plot
plt.show()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, MonthLocator
import seaborn as sns
import tkinter as tk
from tkinter import filedialog
# Set modern style
sns.set(style="whitegrid")
plt.style.use('ggplot')
# Hide Tkinter root window
tk.Tk().withdraw()
# Ask user to select a CSV file
csv_file = filedialog.askopenfilename(
title="Select CSV file",
filetypes=[("CSV files", "*.csv")]
)
if not csv_file:
print("No file selected. Exiting.")
exit()
# Load data from CSV
df = pd.read_csv(csv_file)
# Convert 'Date' column to datetime
df['Date'] = pd.to_datetime(df['Date'])
# Sort by date (if not already sorted)
df = df.sort_values('Date').reset_index(drop=True)
# --- Function to find delay between rainfall event and groundwater response ---
def find_delay(rainfall, groundwater, date, threshold=5, window=30):
"""
Find the delay (in days) between a significant rainfall event and the corresponding
groundwater response.
Parameters:
- rainfall: Series of rainfall data
- groundwater: Series of groundwater data
- date: Series of dates
- threshold: Minimum rainfall (mm) to consider as a significant event
- window: Number of days to look ahead for groundwater response
Returns:
- List of tuples: (rainfall_date, response_date, delay_days)
"""
delays = []
significant_rainfall = rainfall > threshold
for idx in significant_rainfall[significant_rainfall].index:
rain_date = date[idx]
rain_value = rainfall[idx]
# Look for groundwater response within the window
start_idx = idx
end_idx = min(idx + window, len(groundwater))
gw_window = groundwater[start_idx:end_idx]
if len(gw_window) > 0:
# Find the index of the maximum groundwater level in the window
response_idx = gw_window.idxmax()
if not pd.isna(response_idx): # Ensure a valid response is found
response_date = date[response_idx]
delay_days = (response_date - rain_date).days
delays.append((rain_date, response_date, delay_days))
return delays
# --- Calculate delays ---
rainfall = df['Rainfall (mm)']
groundwater = df['Groundwater Level (m)']
date = df['Date']
delays = find_delay(rainfall, groundwater, date, threshold=5, window=30)
# Print delays for reference
if delays:
print("Delays between significant rainfall events and groundwater response:")
for rain_date, response_date, delay_days in delays:
print(f"Rainfall on {rain_date.date()} -> Groundwater response on {response_date.date()} (Delay: {delay_days} days)")
else:
print("No significant rainfall events or groundwater responses found.")
# Create figure and axes
fig, ax1 = plt.subplots(figsize=(14, 7))
# --- Plot Rainfall on top (above x-axis) ---
rain_bars = ax1.bar(df['Date'], df['Rainfall (mm)'], color='#2E86AB', label='Rainfall', width=0.8)
ax1.set_xlabel('Date', fontsize=14, labelpad=10)
ax1.set_ylabel('Rainfall (mm)', color='#2E86AB', fontsize=14)
ax1.tick_params(axis='y', labelcolor='#2E86AB')
# --- Plot Groundwater below x-axis (in 4th quadrant) ---
ax2 = ax1.twinx()
groundwater = -df['Groundwater Level (m)']
smoothed_groundwater = groundwater.rolling(window=7, center=True).mean() # Smooth the line
ground_line, = ax2.plot(df['Date'], smoothed_groundwater, color='#28A745',
linewidth=2.5, linestyle='-', marker='o', markersize=6,
label='Groundwater Level')
ax2.set_ylabel('Groundwater Level (m)', color='#28A745', fontsize=14)
ax2.tick_params(axis='y', labelcolor='#28A745')
# --- Highlight Delays on Plot ---
for rain_date, response_date, delay_days in delays:
# Highlight rainfall event
ax1.axvline(x=rain_date, color='#2E86AB', linestyle='--', alpha=0.5, label='Rainfall Event' if rain_date == delays[0][0] else "")
# Highlight groundwater response
ax2.axvline(x=response_date, color='#28A745', linestyle='--', alpha=0.5, label='Groundwater Response' if rain_date == delays[0][0] else "")
# Add shaded region to show delay
ax1.axvspan(rain_date, response_date, color='gray', alpha=0.2, label='Delay Period' if rain_date == delays[0][0] else "")
# Annotate delay
mid_date = rain_date + (response_date - rain_date) / 2
ax1.text(mid_date, ax1.get_ylim()[1] * 0.9, f'{delay_days} days',
ha='center', va='center', fontsize=10, color='black', bbox=dict(facecolor='white', alpha=0.8))
# --- Formatting X-Axis with Monthly Ticks ---
ax1.xaxis.set_major_locator(MonthLocator()) # Set ticks at the start of each month
ax1.xaxis.set_major_formatter(DateFormatter("%b %Y")) # Format as "Month Year"
fig.autofmt_xdate() # Rotate and align the tick labels
# Horizontal line at y=0 for clarity
ax1.axhline(0, color='black', linewidth=1, linestyle='--', alpha=0.6)
# Title and subtitle
plt.title('Daily Rainfall (Above) and Groundwater Level (Below)\n[With Percolation Delay Highlighted]',
fontsize=16, pad=20, fontweight='bold')
# Add grid manually for better control
ax1.grid(True, which='major', axis='y', linestyle='--', linewidth=0.5, alpha=0.7)
# --- Legend Setup ---
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
# Combine legends and remove duplicates
from collections import OrderedDict
handles, labels = lines1 + lines2, labels1 + labels2
by_label = OrderedDict(zip(labels, handles))
ax1.legend(by_label.values(), by_label.keys(), loc='upper right', fontsize=12, frameon=True, shadow=True)
# Adjust layout
fig.tight_layout()
# --- Ask where to save the plot ---
save_path = filedialog.asksaveasfilename(
title="Save Plot As",
defaultextension=".png",
filetypes=[
("PNG Image", "*.png"),
("PDF Document", "*.pdf"),
("JPEG Image", "*.jpg"),
("SVG Vector", "*.svg"),
("All Files", "*.*")
]
)
if save_path:
try:
fig.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Plot saved successfully to: {save_path}")
except Exception as e:
print(f"Error saving file: {e}")
else:
print("Save canceled.")
# Show plot
plt.show()