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
   6 setup_style()
   7 np.random.seed(42)
   8 
   9 n = 500
  10 x = np.concatenate([np.random.normal(2, 1, n//2), np.random.normal(6, 1.5, n//2)])
  11 y = np.concatenate([np.random.normal(4, 1, n//2), np.random.normal(7, 1.2, n//2)])
  12 
  13 fig = plt.figure(figsize=(7, 7))
  14 gs = gridspec.GridSpec(2, 2, width_ratios=[4, 1], height_ratios=[1, 4],
  15                        hspace=0.05, wspace=0.05)
  16 ax_main = fig.add_subplot(gs[1, 0])
  17 ax_top = fig.add_subplot(gs[0, 0], sharex=ax_main)
  18 ax_right = fig.add_subplot(gs[1, 1], sharey=ax_main)
  19 
  20 # KDE 热力
  21 kde = gaussian_kde(np.vstack([x, y]))
  22 xg = np.linspace(x.min()-1, x.max()+1, 100)
  23 yg = np.linspace(y.min()-1, y.max()+1, 100)
  24 Xg, Yg = np.meshgrid(xg, yg)
  25 Zg = kde(np.vstack([Xg.ravel(), Yg.ravel()])).reshape(Xg.shape)
  26 ax_main.contourf(Xg, Yg, Zg, levels=12, cmap='Blues', alpha=0.5)
  27 ax_main.scatter(x, y, s=8, alpha=0.3, color=PALETTE[0], edgecolor='none')
  28 
  29 # 回归线
  30 z = np.polyfit(x, y, 1)
  31 p = np.poly1d(z)
  32 x_line = np.linspace(x.min(), x.max(), 100)
  33 se_line = np.std(y - p(x)) * np.sqrt(1/n + (x_line - x.mean())**2 / np.sum((x - x.mean())**2))
  34 ax_main.plot(x_line, p(x_line), '--', color=PALETTE[1], linewidth=2, label='回归线')
  35 ax_main.fill_between(x_line, p(x_line) - 1.96*se_line, p(x_line) + 1.96*se_line,
  36                      alpha=0.15, color=PALETTE[1])
  37 ax_main.legend(loc='upper left', fontsize=10, framealpha=0.9)
  38 ax_main.set_xlabel('X 变量', fontsize=11); ax_main.set_ylabel('Y 变量', fontsize=11)
  39 
  40 # 边际 KDE
  41 kde_x = gaussian_kde(x)
  42 xx = np.linspace(x.min()-1, x.max()+1, 200)
  43 ax_top.fill_between(xx, kde_x(xx), alpha=0.3, color=PALETTE[0])
  44 ax_top.plot(xx, kde_x(xx), color=PALETTE[0], linewidth=1.5)
  45 plt.setp(ax_top.get_xticklabels(), visible=False)
  46 
  47 kde_y = gaussian_kde(y)
  48 yy = np.linspace(y.min()-1, y.max()+1, 200)
  49 ax_right.fill_betweenx(yy, kde_y(yy), alpha=0.3, color=PALETTE[1])
  50 ax_right.plot(kde_y(yy), yy, color=PALETTE[1], linewidth=1.5)
  51 plt.setp(ax_right.get_yticklabels(), visible=False)
  52 
  53 for a in [ax_main, ax_top, ax_right]:
  54     a.spines['top'].set_visible(False); a.spines['right'].set_visible(False)
  55 fig.tight_layout()
  56 save_fig(fig, 'figures/fig_kde_joint.pdf')