Here's the enhanced code that explicitly shows the percolation delay between rainfall events and groundwater response using annotations and time-shifted data:
import pandas as pd
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)
# --- User-defined parameters ---
percolation_lag = 10 # Days for water to reach groundwater (adjust based on your data)
peak_date_example = '2024-03-15' # Example rainfall peak date (modify to match your data)
# Create figure and axes
fig, ax1 = plt.subplots(figsize=(14, 7))
# --- Plot Rainfall on top ---
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 Groundwater ---
ax2 = ax1.twinx()
original_groundwater = -df['Groundwater Level (m)']
ax2.plot(df['Date'], original_groundwater,
color='#28A745', linewidth=2.5,
label='Original Groundwater')
# --- Plot Percolation Delay ---
# Create delayed response curve
df['Delayed_Response'] = df['Groundwater Level (m)'].shift(-percolation_lag)
delayed_line, = ax2.plot(df['Date'], -df['Delayed_Response'],
color='#FF5733', linewidth=2.5, linestyle='--',
label=f'Groundwater +{percolation_lag} days')
# --- Add Delay Visualization ---
# 1. Vertical line for rainfall peak
peak_date = pd.to_datetime(peak_date_example)
ax1.axvline(peak_date, color='purple', linestyle=':', alpha=0.8, linewidth=1.5)
# 2. Horizontal line for delayed response
response_date = peak_date + pd.Timedelta(days=percolation_lag)
ax2.axvline(response_date, color='orange', linestyle=':', alpha=0.8, linewidth=1.5)
# 3. Curved arrow connecting events
ax1.annotate('',
xy=(peak_date, 0), # Start at rainfall peak
xytext=(response_date, -df['Groundwater Level (m)'].loc[df['Date'] == response_date].values[0]), # End at groundwater response
arrowprops=dict(arrowstyle='<->', color='purple',
connectionstyle='arc3,rad=0.2',
linewidth=1.5),
)
# 4. Text annotation
ax1.text(peak_date + pd.Timedelta(days=percolation_lag/2),
0.5, f'{percolation_lag} days\npercolation',
ha='center', va='bottom', color='purple', fontsize=10)
# --- Formatting ---
date_format = DateFormatter("%b %Y")
ax1.xaxis.set_major_formatter(date_format)
ax1.xaxis.set_major_locator(MonthLocator())
fig.autofmt_xdate()
# Add horizontal line at y=0
ax1.axhline(0, color='black', linewidth=1, linestyle='--', alpha=0.6)
# Add title with delay info
plt.title(f'Rainfall vs Groundwater with {percolation_lag}-Day Percolation Delay\n'
f'Example: March 15 Rainfall → March 25 Groundwater Response',
fontsize=16, pad=20, fontweight='bold')
# Add grid and legend
ax1.grid(True, which='major', axis='y', linestyle='--', linewidth=0.5, alpha=0.7)
ax1.legend(loc='upper left', fontsize=12)
ax2.legend(loc='upper right', fontsize=12)
# --- Save functionality ---
save_path = filedialog.asksaveasfilename(
title="Save Plot As",
defaultextension=".png",
filetypes=[
("PNG Image", "*.png"),
("PDF Document", "*.pdf"),
("JPEG Image", "*.jpg"),
("SVG Vector", "*.svg")
]
)
if save_path:
fig.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Plot saved to: {save_path}")
plt.tight_layout()
plt.show()