1 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten 2 setup_style() 3 import matplotlib.pyplot as plt 4 import matplotlib.gridspec as gridspec 5 import numpy as np 6 7 np.random.seed(42) 8 features = ['Feature A', 'Feature B', 'Feature C', 'Feature D', 'Feature E'] 9 n_samples = 200 10 11 fig = plt.figure(figsize=(9, 5)) 12 gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1], wspace=0.05) 13 14 # Left panel: SHAP beeswarm 15 ax_shap = fig.add_subplot(gs[0]) 16 ax_shap.grid(axis='x', alpha=0.15, linestyle='-', color=COLORS['grid']) 17 ax_shap.set_axisbelow(True) 18 19 mean_abs_shap = [] 20 for i, feat in enumerate(features): 21 shap_vals = np.random.randn(n_samples) * (len(features) - i) * 0.12 22 feat_vals = np.random.rand(n_samples) 23 y_jitter = np.random.uniform(-0.3, 0.3, n_samples) + i 24 sc = ax_shap.scatter(shap_vals, y_jitter, c=feat_vals, cmap='coolwarm', 25 s=10, alpha=0.65, vmin=0, vmax=1, edgecolors='none') 26 mean_abs_shap.append(np.mean(np.abs(shap_vals))) 27 28 ax_shap.set_yticks(range(len(features))) 29 ax_shap.set_yticklabels(features, fontsize=10) 30 ax_shap.set_xlabel('SHAP value (impact on prediction)', fontsize=10) 31 ax_shap.axvline(x=0, color=COLORS['ref_line'], linewidth=0.8, linestyle='--') 32 ax_shap.spines['top'].set_visible(False) 33 ax_shap.spines['right'].set_visible(False) 34 35 # Colorbar 36 cbar = plt.colorbar(sc, ax=ax_shap, shrink=0.5, pad=0.02, aspect=20) 37 cbar.set_label('Feature value', fontsize=8) 38 cbar.ax.tick_params(labelsize=7) 39 40 # Right panel: Mean |SHAP| importance bar —— 浅色填充 + 原色边框 41 ax_bar = fig.add_subplot(gs[1]) 42 for i, v in enumerate(mean_abs_shap): 43 is_top = (v == max(mean_abs_shap)) 44 c = PALETTE[0] if is_top else PALETTE[2] 45 ax_bar.barh(i, v, color=_lighten(c, 0.4), edgecolor=c, 46 linewidth=1.5, height=0.5, alpha=0.9) 47 ax_bar.text(v + 0.002, i, f'{v:.3f}', va='center', fontsize=8, color=COLORS['text']) 48 ax_bar.set_yticks([]) 49 ax_bar.set_xlabel('Mean |SHAP|', fontsize=9) 50 ax_bar.spines['top'].set_visible(False) 51 ax_bar.spines['right'].set_visible(False) 52 ax_bar.spines['left'].set_visible(False) 53 54 fig.tight_layout() 55 save_fig(fig, 'figures/fig_shap.pdf')