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 = 150 8 x = np.random.normal(5, 2, n) 9 y = 0.6*x + np.random.normal(0, 1.5, n) 10 z = np.random.uniform(10, 80, n) 11 12 fig = plt.figure(figsize=(7, 7)) 13 gs = fig.add_gridspec(2, 2, width_ratios=[4, 1], height_ratios=[1, 4], 14 hspace=0.05, wspace=0.05) 15 ax_main = fig.add_subplot(gs[1, 0]) 16 ax_top = fig.add_subplot(gs[0, 0], sharex=ax_main) 17 ax_right = fig.add_subplot(gs[1, 1], sharey=ax_main) 18 19 # 主图:气泡 20 sc = ax_main.scatter(x, y, s=z*3, c=z, cmap='YlOrRd', alpha=0.6, 21 edgecolor='white', linewidth=0.5) 22 ax_main.set_xlabel('变量 X', fontsize=11); ax_main.set_ylabel('变量 Y', fontsize=11) 23 24 # 上方 KDE 25 kde_x = gaussian_kde(x) 26 xx = np.linspace(x.min()-1, x.max()+1, 200) 27 ax_top.fill_between(xx, kde_x(xx), alpha=0.3, color=PALETTE[0]) 28 ax_top.plot(xx, kde_x(xx), color=PALETTE[0], linewidth=1.5) 29 ax_top.set_ylabel('密度', fontsize=9) 30 plt.setp(ax_top.get_xticklabels(), visible=False) 31 32 # 右方 KDE 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 ax_right.set_xlabel('密度', fontsize=9) 38 plt.setp(ax_right.get_yticklabels(), visible=False) 39 40 for a in [ax_main, ax_top, ax_right]: 41 a.spines['top'].set_visible(False); a.spines['right'].set_visible(False) 42 43 fig.colorbar(sc, ax=ax_right, shrink=0.6, label='气泡大小 Z') 44 fig.tight_layout() 45 save_fig(fig, 'figures/fig_bubble_joint.pdf')