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 = 300
  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, 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 ax_main.scatter(x, y, s=15, alpha=0.4, color=PALETTE[0], edgecolor='white', linewidth=0.3)
  21 z = np.polyfit(x, y, 1); p = np.poly1d(z)
  22 x_line = np.linspace(x.min(), x.max(), 100)
  23 ax_main.plot(x_line, p(x_line), '--', color=PALETTE[1], linewidth=2, label=f'y={z[0]:.2f}x{z[1]:+.1f}')
  24 ax_main.legend(loc='upper left', fontsize=9)
  25 ax_main.set_xlabel('X 变量', fontsize=11); ax_main.set_ylabel('Y 变量', fontsize=11)
  26 
  27 kde_x = gaussian_kde(x)
  28 xx = np.linspace(x.min()-0.5, x.max()+0.5, 200)
  29 ax_top.fill_between(xx, kde_x(xx), alpha=0.3, color=PALETTE[0])
  30 ax_top.plot(xx, kde_x(xx), color=PALETTE[0], linewidth=1.5)
  31 plt.setp(ax_top.get_xticklabels(), visible=False)
  32 
  33 kde_y = gaussian_kde(y)
  34 yy = np.linspace(y.min()-1, y.max()+1, 200)
  35 ax_right.fill_betweenx(yy, kde_y(yy), alpha=0.3, color=PALETTE[1])
  36 ax_right.plot(kde_y(yy), yy, color=PALETTE[1], linewidth=1.5)
  37 plt.setp(ax_right.get_yticklabels(), visible=False)
  38 
  39 for a in [ax_main, ax_top, ax_right]:
  40     a.spines['top'].set_visible(False); a.spines['right'].set_visible(False)
  41 fig.tight_layout()
  42 save_fig(fig, 'figures/fig_scatter_marginal.pdf')