Nice — below is a ready-to-run Python function that creates pairwise plots for your 4 variables (works for any number of variables). For each variable pair it draws a scatter plot with 2-D KDE contours on the lower triangle, 1-D density plots on the diagonal, and writes the Pearson correlation coefficient (and p-value) on the upper triangle. It also prints the correlation matrix.
Usage notes (quick):
If you already have a pandas.DataFrame df with your 4 columns, call pairwise_plots(df, cols) where cols is a list of column names (or omit cols to use all numeric columns).
Or save your data as CSV and pass the path to read_csv_path (see example).
pythonCopy code# pairwise_plots.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from typing import List, Optional, Union
sns.set(style="white") # clean style
def pairwise_plots(
df: Optional[pd.DataFrame] = None,
cols: Optional[List[str]] = None,
read_csv_path: Optional[str] = None,
figsize: Optional[tuple] = None,
savepath: Optional[str] = None,
kde_levels: int = 6
):
"""
Create pairwise plots for variables in df (or CSV file).
- Lower triangle: scatter + 2D KDE contours
- Diagonal: 1D KDE (density)
- Upper triangle: Pearson r and p-value annotated
code
Parameters
----------
df : pd.DataFrame or None
DataFrame containing measured variables. If None, provide read_csv_path.
cols : list[str] or None
List of column names to include (default: all numeric columns in df).
read_csv_path : str or None
Path to CSV file to read instead of providing df directly.
figsize : tuple or None
Figure size; by default calculated from number of variables.
savepath : str or None
If provided, saves the figure to this path (e.g., "pairwise.png").
kde_levels : int
Number of contour levels for 2D KDE.
"""
# Load data
if df is None:
if read_csv_path is None:
raise ValueError("Either provide a DataFrame `df` or `read_csv_path`.")
df = pd.read_csv(read_csv_path)
if cols is None:
# pick numeric columns by default
cols = df.select_dtypes(include=[np.number]).columns.tolist()
df = df.loc[:, cols].copy()
# Basic checks
if df.shape[1] < 2:
raise ValueError("Need at least two numeric columns to plot pairwise relationships.")
# compute correlation matrix (Pearson)
corr = df.corr(method='pearson')
print("Pearson correlation matrix:")
print(corr.round(4))
n = df.shape[1]
if figsize is None:
figsize = (2.8 * n, 2.8 * n)
# Custom plotting functions for PairGrid
def scatter_kde(x, y, **kwargs):
ax = plt.gca()
# scatter
ax.scatter(x, y, s=12, alpha=0.6, edgecolors='none')
# 2D KDE contours - drop NA
valid = (~np.isnan(x)) & (~np.isnan(y))
if valid.sum() >= 3:
try:
sns.kdeplot(x=x[valid], y=y[valid], levels=kde_levels, linewidths=1, ax=ax, alpha=0.8)
except Exception:
# fallback: no KDE if it fails
pass
def diag_kde(x, **kwargs):
ax = plt.gca()
# 1D KDE for the diagonal
valid = x[~np.isnan(x)]
if valid.size > 1:
sns.kdeplot(valid, fill=True, ax=ax)
else:
# fallback to histogram if not enough points
ax.hist(valid, bins=5)
def corr_annot(x, y, **kwargs):
ax = plt.gca()
# pairwise dropna
valid = (~np.isnan(x)) & (~np.isnan(y))
if valid.sum() >= 2:
r, p = stats.pearsonr(x[valid], y[valid])
annot = f"r = {r:.3f}\np = {p:.2e}"
else:
annot = "r = n/a\np = n/a"
# center the text
ax.annotate(annot, xy=(0.5, 0.5), xycoords='axes fraction',
ha='center', va='center', fontsize=10, fontweight='semibold')
# remove ticks for clarity
ax.set_xticks([])
ax.set_yticks([])
# Build PairGrid
grid = sns.PairGrid(df, vars=cols, diag_sharey=False, height=2.6)
grid.map_lower(scatter_kde)
grid.map_diag(diag_kde)
grid.map_upper(corr_annot)
# Improve layout: rotate x labels, tighten
for ax in grid.axes.flatten():
# ensure tick params are readable
if ax is not None:
for label in ax.get_xticklabels():
label.set_rotation(25)
label.set_horizontalalignment('right')
for label in ax.get_yticklabels():
label.set_rotation(0)
plt.subplots_adjust(top=0.95, hspace=0.12, wspace=0.12)
grid.fig.suptitle("Pairwise scatter + density plots\n(upper: Pearson r and p-value)", fontsize=14)
if savepath:
plt.savefig(savepath, dpi=300, bbox_inches='tight')
print(f"Saved figure to {savepath}")
plt.show()
---------------------------
Example usage:
if name == "main":
# Example 1: If you already have a DataFrame df (replace with your data)
# df = pd.DataFrame({
# "var1": [...],
# "var2": [...],
# "var3": [...],
# "var4": [...],
# })
# pairwise_plots(df, cols=["var1","var2","var3","var4"], savepath="pairs.png")
code
# Example 2: Read from CSV
# pairwise_plots(read_csv_path="my_measurements.csv", cols=["A","B","C","D"], savepath="pairs.png")
# Example 3: Quick demo with synthetic data (runs when file is executed directly)
np.random.seed(0)
demo_df = pd.DataFrame({
"A": np.random.normal(0, 1, 200),
"B": np.random.normal(1, 1.5, 200) + np.linspace(0, 1, 200) * 0.8,
"C": np.random.exponential(1.0, 200),
"D": np.random.normal(-0.5, 0.8, 200) + np.random.normal(0, 0.3, 200)
})
pairwise_plots(demo_df, cols=["A","B","C","D"])
If you'd like, I can:
adapt the function to show Spearman instead of Pearson correlations,
annotate the exact correlation value on each lower-plot directly,
or run the code here with your actual data if you paste the numbers or upload a CSV.