Certainly!
To automatically detect multiple rainfall peaks and calculate the lag for each peak (i.e., the time between a rainfall peak and the corresponding groundwater response), you can use the following approach:
- Detect rainfall peaks (using
scipy.signal.find_peaks).
- For each rainfall peak, search for the corresponding groundwater response peak within a reasonable window after the rainfall event.
- Calculate the lag for each event.
- Plot and annotate the lags on the graph.
- Show the average lag in the title.
Below is a complete, ready-to-run code:
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
from scipy.signal import find_peaks
# 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)
df['Date'] = pd.to_datetime(df['Date'])
df = df.sort_values('Date').reset_index(drop=True)
df = df.dropna(subset=['Rainfall (mm)', 'Groundwater Level (m)'])
# --- Detect rainfall peaks ---
rain = df['Rainfall (mm)']
rain_peaks, _ = find_peaks(rain, height=np.percentile(rain, 75), distance=5) # Adjust threshold/distance as needed
# --- Detect groundwater peaks (inverted, as lower values mean higher water table) ---
gw = -df['Groundwater Level (m)']
gw_peaks, _ = find_peaks(gw, distance=5) # Adjust distance as needed
# --- For each rainfall peak, find the nearest groundwater peak after it within a window ---
lags = []
annotations = []
search_window = 30 # days after rainfall peak to look for GW response
for rp in rain_peaks:
rain_date = df.loc[rp, 'Date']
# Find GW peaks after rainfall peak within window
possible_gw_peaks = [gp for gp in gw_peaks if 0 < (df.loc[gp, 'Date'] - rain_date).days <= search_window]
if possible_gw_peaks:
# Take the first GW peak after rainfall peak
gp = possible_gw_peaks[0]
gw_date = df.loc[gp, 'Date']
lag = (gw_date - rain_date).days
lags.append(lag)
annotations.append((rain_date, gw_date, rp, gp))
# --- Plotting ---
fig, ax1 = plt.subplots(figsize=(14, 7))
# Rainfall
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')
# Groundwater (original)
ax2 = ax1.twinx()
ax2.plot(df['Date'], -df['Groundwater Level (m)'], color='#28A745', linewidth=2.5, label='Groundwater Level')
# Annotate peaks and lags
for rain_date, gw_date, rp, gp in annotations:
ax1.axvline(rain_date, color='purple', linestyle=':', alpha=0.7, linewidth=1)
ax2.axvline(gw_date, color='orange', linestyle=':', alpha=0.7, linewidth=1)
ax1.annotate('',
xy=(rain_date, df.loc[rp, 'Rainfall (mm)']),
xytext=(gw_date, -df.loc[gp, 'Groundwater Level (m)']),
arrowprops=dict(arrowstyle='<->', color='red', connectionstyle='arc3,rad=0.2', linewidth=1.5),
)
ax1.text(rain_date + (gw_date - rain_date) / 2,
max(df['Rainfall (mm)']) * 0.8,
f'{(gw_date - rain_date).days}d',
ha='center', va='bottom', color='red', fontsize=9, rotation=90)
# Formatting
date_format = DateFormatter("%b %Y")
ax1.xaxis.set_major_formatter(date_format)
ax1.xaxis.set_major_locator(MonthLocator())
fig.autofmt_xdate()
ax1.axhline(0, color='black', linewidth=1, linestyle='--', alpha=0.6)
# Title with average lag
if lags:
avg_lag = np.mean(lags)
plt.title(f'Rainfall vs Groundwater: Avg. Response Lag = {avg_lag:.1f} Days (Multiple Peaks)', fontsize=16, pad=20, fontweight='bold')
else:
plt.title('Rainfall vs Groundwater: No Response Detected', fontsize=16, pad=20, fontweight='bold')
ax1.grid(True, which='major', axis='y', linestyle='--', linewidth=0.5, alpha=0.7)
# Combine legends (top right)
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)
# Right axis label
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()