1 import numpy as np 2 import matplotlib.pyplot as plt 3 import matplotlib.colors as mcolors 4 from _utils.plot_utils import setup_style, save_fig, PALETTE, smart_labels, auto_legend 5 setup_style() 6 7 # === Example data (replace with your PCA results) === 8 np.random.seed(42) 9 n_samples, n_features = 80, 12 10 feature_names = ['市场规模', '供应链成熟度', '短期恢复能力', '响应梯度元素', 11 '长期恢复速度', '研发投入强度', '短期恢复弹性', '产能利用率', 12 '短期集中度', '专利授权量', '产业链完整度', '客户集中度'] 13 14 # Simulated PCA scores and loadings 15 scores = np.random.randn(n_samples, 2) * 2 16 loadings = np.random.randn(n_features, 2) 17 loadings = loadings / np.abs(loadings).max(axis=0) * 3 # scale to [-3, 3] 18 explained_var = [66.3, 11.4] # explained variance % 19 20 fig, ax = plt.subplots(figsize=(8, 7)) 21 22 # Scatter: sample scores (gray, semi-transparent) 23 ax.scatter(scores[:, 0], scores[:, 1], s=25, alpha=0.35, color=COLORS['gray'], 24 edgecolors='white', linewidths=0.3, zorder=2) 25 26 # Loading arrows 27 arrow_colors = [] 28 for i, (name, lx, ly) in enumerate(zip(feature_names, loadings[:, 0], loadings[:, 1])): 29 magnitude = np.sqrt(lx**2 + ly**2) 30 color = PALETTE[0] 31 arrow_colors.append(color) 32 ax.annotate('', xy=(lx, ly), xytext=(0, 0), 33 arrowprops=dict(arrowstyle='->', color=color, lw=1.5, alpha=0.7)) 34 35 # ── 特征名标签 —— smart_labels 自动推开重叠标签 36 # Offset labels slightly beyond arrow tips 37 label_xs = [lx * 1.08 for lx in loadings[:, 0]] 38 label_ys = [ly * 1.08 for ly in loadings[:, 1]] 39 smart_labels(ax, label_xs, label_ys, feature_names, 40 colors=arrow_colors, fontsize=8.5, fontweight='bold', 41 offset=(5, 0), 42 bbox=dict(boxstyle='round,pad=0.2', facecolor='white', 43 edgecolor=PALETTE[0], alpha=0.8, linewidth=0.5), 44 arrowprops=dict(arrowstyle='-', color=COLORS['grid'], lw=0.4), 45 force_text=0.8, force_points=0.5) 46 47 # Reference lines 48 ax.axhline(0, color=COLORS['ref_line'], linewidth=0.5, alpha=0.4) 49 ax.axvline(0, color=COLORS['ref_line'], linewidth=0.5, alpha=0.4) 50 51 ax.set_xlabel(f'PC1 ({explained_var[0]:.1f}%)', fontsize=11) 52 ax.set_ylabel(f'PC2 ({explained_var[1]:.1f}%)', fontsize=11) 53 ax.spines['top'].set_visible(False) 54 ax.spines['right'].set_visible(False) 55 ax.grid(alpha=0.1, linestyle='--') 56 fig.tight_layout() 57 save_fig(fig, 'figures/fig_pca_biplot.pdf')