1 import numpy as np 2 import matplotlib.pyplot as plt 3 import matplotlib.gridspec as gridspec 4 from scipy.stats import gaussian_kde 5 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten 6 setup_style() 7 8 np.random.seed(42) 9 n = 150 10 x = np.random.uniform(1, 10, n) 11 y = 2.5 * x + np.random.normal(0, 3, n) 12 13 fig = plt.figure(figsize=(7, 6)) 14 gs = gridspec.GridSpec(2, 2, width_ratios=[4, 1], height_ratios=[1, 4], 15 wspace=0.05, hspace=0.05) 16 17 ax_main = fig.add_subplot(gs[1, 0]) 18 ax_top = fig.add_subplot(gs[0, 0], sharex=ax_main) 19 ax_right = fig.add_subplot(gs[1, 1], sharey=ax_main) 20 21 # KDE 等高线背景 22 xy = np.vstack([x, y]) 23 kde = gaussian_kde(xy, bw_method=0.3) 24 xg = np.linspace(x.min() - 1, x.max() + 1, 80) 25 yg = np.linspace(y.min() - 3, y.max() + 3, 80) 26 Xg, Yg = np.meshgrid(xg, yg) 27 Z = kde(np.vstack([Xg.ravel(), Yg.ravel()])).reshape(Xg.shape) 28 ax_main.contourf(Xg, Yg, Z, levels=8, cmap='Blues', alpha=0.15) 29 ax_main.contour(Xg, Yg, Z, levels=5, colors=PALETTE[0], alpha=0.2, linewidths=0.5) 30 31 # 散点 32 ax_main.scatter(x, y, s=30, alpha=0.5, color=PALETTE[0], edgecolor='white', linewidth=0.5, zorder=3) 33 34 # 拟合线 + 置信带 35 z = np.polyfit(x, y, 1) 36 p = np.poly1d(z) 37 x_fit = np.linspace(x.min(), x.max(), 100) 38 ax_main.plot(x_fit, p(x_fit), color=PALETTE[1], linewidth=2, zorder=4) 39 residuals = y - p(x) 40 se = residuals.std() 41 for layer, alpha in enumerate([0.15, 0.08, 0.03]): 42 ax_main.fill_between(x_fit, p(x_fit) - 1.96 * se * (0.3 + layer * 0.1), 43 p(x_fit) + 1.96 * se * (0.3 + layer * 0.1), 44 alpha=alpha, color=PALETTE[1], linewidth=0) 45 46 # R² 标注框 47 r2 = 1 - np.sum(residuals ** 2) / np.sum((y - y.mean()) ** 2) 48 ax_main.text(0.05, 0.92, f'R² = {r2:.3f}\ny = {z[0]:.2f}x + {z[1]:.2f}\nn = {n}', 49 transform=ax_main.transAxes, fontsize=9, verticalalignment='top', 50 bbox=dict(boxstyle='round,pad=0.4', facecolor='white', 51 edgecolor=PALETTE[0], alpha=0.9, linewidth=0.8)) 52 53 # 边际密度(顶部) 54 kde_x = gaussian_kde(x, bw_method=0.3) 55 xd = np.linspace(x.min() - 1, x.max() + 1, 200) 56 ax_top.fill_between(xd, kde_x(xd), alpha=0.2, color=PALETTE[0]) 57 ax_top.plot(xd, kde_x(xd), color=PALETTE[0], linewidth=1.2) 58 ax_top.set_yticks([]) 59 ax_top.spines['top'].set_visible(False) 60 ax_top.spines['right'].set_visible(False) 61 ax_top.spines['left'].set_visible(False) 62 plt.setp(ax_top.get_xticklabels(), visible=False) 63 64 # 边际密度(右侧) 65 kde_y = gaussian_kde(y, bw_method=0.3) 66 yd = np.linspace(y.min() - 3, y.max() + 3, 200) 67 ax_right.fill_betweenx(yd, kde_y(yd), alpha=0.2, color=PALETTE[0]) 68 ax_right.plot(kde_y(yd), yd, color=PALETTE[0], linewidth=1.2) 69 ax_right.set_xticks([]) 70 ax_right.spines['top'].set_visible(False) 71 ax_right.spines['right'].set_visible(False) 72 ax_right.spines['bottom'].set_visible(False) 73 plt.setp(ax_right.get_yticklabels(), visible=False) 74 75 ax_main.set_xlabel('自变量 X', fontsize=11) 76 ax_main.set_ylabel('因变量 Y', fontsize=11) 77 ax_main.grid(alpha=0.12, linestyle='--', color=COLORS['grid']) 78 ax_main.spines['top'].set_visible(False) 79 ax_main.spines['right'].set_visible(False) 80 fig.tight_layout() 81 save_fig(fig, 'figures/fig_scatter.pdf')