1 import numpy as np, matplotlib.pyplot as plt
   2 from scipy.stats import gaussian_kde
   3 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS
   4 setup_style()
   5 np.random.seed(42)
   6 
   7 n = 300
   8 x = np.concatenate([np.random.normal(3, 1, n//2), np.random.normal(7, 1.5, n//2)])
   9 y = np.concatenate([np.random.normal(5, 1.2, n//2), np.random.normal(3, 1, n//2)])
  10 
  11 fig, ax = plt.subplots(figsize=(7, 6))
  12 # KDE 等高线
  13 kde = gaussian_kde(np.vstack([x, y]))
  14 xg = np.linspace(x.min()-1, x.max()+1, 100)
  15 yg = np.linspace(y.min()-1, y.max()+1, 100)
  16 Xg, Yg = np.meshgrid(xg, yg)
  17 Zg = kde(np.vstack([Xg.ravel(), Yg.ravel()])).reshape(Xg.shape)
  18 ax.contourf(Xg, Yg, Zg, levels=10, cmap='Blues', alpha=0.3)
  19 ax.contour(Xg, Yg, Zg, levels=6, colors=PALETTE[0], linewidths=0.8, alpha=0.5)
  20 
  21 # 散点
  22 ax.scatter(x, y, s=12, alpha=0.4, color=PALETTE[0], edgecolor='white', linewidth=0.3)
  23 
  24 ax.set_xlabel('变量 X', fontsize=11); ax.set_ylabel('变量 Y', fontsize=11)
  25 ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  26 fig.tight_layout()
  27 save_fig(fig, 'figures/fig_bubble_kde.pdf')