1 import numpy as np 2 import matplotlib.pyplot as plt 3 import matplotlib.gridspec as gridspec 4 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS 5 setup_style() 6 np.random.seed(42) 7 8 n = 2000 9 x = np.random.normal(0, 2, n) 10 y = 0.5*x + np.random.normal(0, 1.5, n) 11 12 fig = plt.figure(figsize=(7, 7)) 13 gs = gridspec.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 # 主图:hexbin 20 hb = ax_main.hexbin(x, y, gridsize=25, cmap='YlOrRd', mincnt=1, edgecolors='white', linewidths=0.3) 21 # 回归线 22 z = np.polyfit(x, y, 1) 23 p = np.poly1d(z) 24 x_line = np.linspace(x.min(), x.max(), 100) 25 ax_main.plot(x_line, p(x_line), '--', color=PALETTE[1], linewidth=1.8, 26 label=f'$\\hat{{Y}}={z[0]:.3f}X{z[1]:+.1f}$') 27 ax_main.legend(loc='lower right', fontsize=9, framealpha=0.9) 28 ax_main.set_xlabel('X 变量', fontsize=11); ax_main.set_ylabel('Y 变量', fontsize=11) 29 30 # 上方直方图 31 ax_top.hist(x, bins=40, color=PALETTE[0], alpha=0.5, edgecolor='white', linewidth=0.5) 32 plt.setp(ax_top.get_xticklabels(), visible=False) 33 ax_top.set_ylabel('频数', fontsize=9) 34 35 # 右方直方图 36 ax_right.hist(y, bins=40, orientation='horizontal', color=PALETTE[1], alpha=0.5, 37 edgecolor='white', linewidth=0.5) 38 plt.setp(ax_right.get_yticklabels(), visible=False) 39 ax_right.set_xlabel('频数', fontsize=9) 40 41 for a in [ax_main, ax_top, ax_right]: 42 a.spines['top'].set_visible(False); a.spines['right'].set_visible(False) 43 44 fig.colorbar(hb, ax=ax_right, shrink=0.6, label='样本数') 45 fig.tight_layout() 46 save_fig(fig, 'figures/fig_hexbin_joint.pdf')