Here's the updated code that automatically calculates the optimal delay (percolation lag) between rainfall and groundwater response using cross-correlation, eliminating the need for manual input. The code dynamically adjusts the delay based on the data, and all legends are placed in the top right corner with the right axis labeled as "Groundwater Level (BGL in m)".
✅ Key Features:
- Automatically calculates the optimal delay (percolation lag) using cross-correlation between rainfall and groundwater data.
- No manual input required for the
percolation_lag.
- All legends are combined and placed in the top right corner.
- Right axis labeled as
"Groundwater Level (BGL in m)".
📁 Final Code
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
import numpy as np
# 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)
# --- Automatically calculate optimal percolation lag ---
def calculate_optimal_lag(df, max_lag=30):
rainfall = df['Rainfall (mm)']
groundwater = df['Groundwater Level (m)']
correlations = []
for lag in range(0, max_lag + 1):
shifted_groundwater = groundwater.shift(-lag)
combined = pd.DataFrame({'rainfall': rainfall, 'groundwater': shifted_groundwater})
combined = combined.dropna()
if len(combined) < 2:
continue
corr = combined.corr().iloc[0, 1]
correlations.append((lag, corr))
if correlations:
best_lag = max(correlations, key=lambda x: x[1])[0]
else:
best_lag = 10 # Default if no correlation found
return best_lag
# Calculate optimal lag (adjust max_lag as needed)
percolation_lag = calculate_optimal_lag(df, max_lag=30)
# 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 (example: first peak)
peak_date = df.loc[df['Rainfall (mm)'].idxmax(), 'Date']
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 dynamic delay info
plt.title(f'Rainfall vs Groundwater with {percolation_lag}-Day Percolation Delay',
fontsize=16, pad=20, fontweight='bold')
# Add grid
ax1.grid(True, which='major', axis='y', linestyle='--', linewidth=0.5, alpha=0.7)
# --- Combine legends and place at top right corner ---
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)
# --- Update right axis title ---
ax2.set_ylabel('Groundwater Level (BGL in m)', color='#28A745', fontsize=14)
ax2.tick_params(axis='y', labelcolor='#28A745')
# --- 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()
🔍 How It Works:
-
Automatic Lag Calculation:
- The
calculate_optimal_lag function uses cross-correlation to find the delay that maximizes the correlation between rainfall and groundwater data.
- This avoids the need for manual input of
percolation_lag.
-
Dynamic Visualization:
- The plot dynamically updates the delay based on the calculated value.
- A vertical line marks the peak rainfall, and a curved arrow shows the delay to the groundwater response.
-
Legend Placement:
- All legends are combined and placed in the top right corner for clarity.
-
Axis Labeling:
- The right y-axis is labeled as
"Groundwater Level (BGL in m)".
📌 Notes:
- The
max_lag parameter can be adjusted based on your dataset (e.g., 30 days for typical groundwater response).
- If the data lacks clear correlation, the code defaults to a
percolation_lag of 10 days.
🧪 Example Output:
If the data shows a 10-day delay between rainfall and groundwater response:
- The plot will display a 10-day delay in the title.
- A curved arrow will connect the rainfall peak to the groundwater response.
- Legends will be in the top right corner.
Would you like to add peak detection or interactive annotations for multiple events? I can help extend this further! 😊