1 import numpy as np 2 import matplotlib.pyplot as plt 3 from scipy.stats import gaussian_kde, pearsonr 4 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten 5 6 setup_style() 7 np.random.seed(42) 8 9 # === 模拟 4 个变量(含正/负/弱相关)=== 10 n = 250 11 v1 = np.random.normal(0, 1, n) 12 v2 = 0.75 * v1 + np.random.normal(0, 0.55, n) # 强正相关 13 v3 = -0.55 * v1 + 0.3 * v2 + np.random.normal(0, 0.7, n) # 中等负相关 14 v4 = np.random.normal(0, 1, n) # 弱相关 15 data = np.column_stack([v1, v2, v3, v4]) 16 names = ['X1', 'X2', 'X3', 'X4'] 17 N = len(names) 18 19 fig, axes = plt.subplots(N, N, figsize=(8.5, 8.5)) 20 21 for i in range(N): 22 for j in range(N): 23 ax = axes[i, j] 24 if i == j: 25 # ★ 对角线:直方图 + KDE 26 ax.hist(data[:, i], bins=22, color=_lighten(PALETTE[i % len(PALETTE)], 0.55), 27 edgecolor=PALETTE[i % len(PALETTE)], linewidth=0.5, alpha=0.85) 28 ax2 = ax.twinx() 29 xg = np.linspace(data[:, i].min(), data[:, i].max(), 200) 30 ax2.plot(xg, gaussian_kde(data[:, i])(xg), 31 color=PALETTE[i % len(PALETTE)], linewidth=1.5) 32 ax2.set_yticks([]) 33 ax2.spines['top'].set_visible(False) 34 ax2.spines['right'].set_visible(False) 35 ax2.spines['left'].set_visible(False) 36 ax.text(0.05, 0.92, names[i], transform=ax.transAxes, 37 fontsize=11, fontweight='bold', color=PALETTE[i % len(PALETTE)], 38 va='top', ha='left') 39 elif i > j: 40 # ★ 下三角:散点 + 拟合线 41 ax.scatter(data[:, j], data[:, i], s=10, alpha=0.35, 42 color=PALETTE[0], edgecolor='white', linewidth=0.2) 43 # 简易线性拟合 44 slope, intercept = np.polyfit(data[:, j], data[:, i], 1) 45 xfit = np.linspace(data[:, j].min(), data[:, j].max(), 60) 46 yfit = slope * xfit + intercept 47 ax.plot(xfit, yfit, color=COLORS['highlight'], linewidth=1.4, 48 alpha=0.85, zorder=5) 49 else: 50 # ★ 上三角:相关系数(按强度上色 + 字号映射强度) 51 r, p = pearsonr(data[:, j], data[:, i]) 52 # 强度映射到背景颜色 53 if r > 0: 54 bg = _lighten(PALETTE[0], 1 - abs(r) * 0.7) 55 else: 56 bg = _lighten(COLORS['down'], 1 - abs(r) * 0.7) 57 ax.set_facecolor(bg) 58 sig = '***' if p < 0.001 else ('**' if p < 0.01 else ('*' if p < 0.05 else '')) 59 fs = 10 + abs(r) * 12 # 字号随 |r| 增大 60 ax.text(0.5, 0.55, f'{r:+.2f}', transform=ax.transAxes, 61 fontsize=fs, fontweight='bold', 62 color=COLORS['text'], ha='center', va='center') 63 if sig: 64 ax.text(0.5, 0.18, sig, transform=ax.transAxes, 65 fontsize=11, color=COLORS['text'], ha='center') 66 67 # 仅在最下/最左行留刻度 68 if i < N - 1: 69 ax.tick_params(axis='x', labelbottom=False) 70 else: 71 ax.tick_params(labelsize=7) 72 if j > 0: 73 ax.tick_params(axis='y', labelleft=False) 74 else: 75 ax.tick_params(labelsize=7) 76 if i != j: 77 ax.spines['top'].set_visible(False) 78 ax.spines['right'].set_visible(False) 79 ax.grid(alpha=0.08, linestyle='--', color=COLORS['grid']) 80 81 fig.tight_layout(pad=0.4) 82 save_fig(fig, 'figures/fig_pair_plot.pdf')