1 import numpy as np; from _utils.palette_maps import palette_cmap, palette_stops, contrast_text
   2 import matplotlib.pyplot as plt
   3 import matplotlib.gridspec as gridspec
   4 import seaborn as sns
   5 from scipy.cluster.hierarchy import dendrogram, linkage
   6 from scipy.spatial.distance import pdist
   7 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
   8 setup_style()
   9 
  10 np.random.seed(42)
  11 labels = ['特征A', '特征B', '特征C', '特征D', '特征E', '特征F']
  12 n = len(labels)
  13 # 生成相关矩阵
  14 data = np.random.randn(100, n)
  15 corr = np.corrcoef(data.T)
  16 
  17 fig = plt.figure(figsize=(8, 7))
  18 gs = gridspec.GridSpec(2, 2, width_ratios=[1, 6], height_ratios=[1, 6],
  19                        wspace=0.02, hspace=0.02)
  20 
  21 # 顶部树状图
  22 ax_dtop = fig.add_subplot(gs[0, 1])
  23 Z = linkage(pdist(corr), method='ward')
  24 dn = dendrogram(Z, ax=ax_dtop, no_labels=True, color_threshold=0,
  25                 above_threshold_color=PALETTE[0])
  26 ax_dtop.set_xticks([])
  27 ax_dtop.set_yticks([])
  28 for spine in ax_dtop.spines.values():
  29     spine.set_visible(False)
  30 
  31 # 左侧树状图
  32 ax_dleft = fig.add_subplot(gs[1, 0])
  33 dendrogram(Z, ax=ax_dleft, orientation='left', no_labels=True,
  34            color_threshold=0, above_threshold_color=PALETTE[0])
  35 ax_dleft.set_xticks([])
  36 ax_dleft.set_yticks([])
  37 for spine in ax_dleft.spines.values():
  38     spine.set_visible(False)
  39 
  40 # 主热力图(下三角遮罩)
  41 ax_heat = fig.add_subplot(gs[1, 1])
  42 mask = np.triu(np.ones_like(corr, dtype=bool), k=1)
  43 corr_masked = np.ma.array(corr, mask=mask)
  44 
  45 im = ax_heat.imshow(corr_masked, cmap=palette_cmap('diverging'), vmin=-1, vmax=1, aspect='auto')
  46 ax_heat.set_xticks(range(n))
  47 ax_heat.set_xticklabels(labels, rotation=45, ha='right', fontsize=9)
  48 ax_heat.set_yticks(range(n))
  49 ax_heat.set_yticklabels(labels, fontsize=9)
  50 
  51 # 数值标注(自动对比度)
  52 for i in range(n):
  53     for j in range(n):
  54         if not mask[i, j]:
  55             val = corr[i, j]
  56             text_color = contrast_text(im.cmap(im.norm(val)))
  57             ax_heat.text(j, i, f'{val:.2f}', ha='center', va='center',
  58                          fontsize=7.5, color=text_color, fontweight='bold' if abs(val) > 0.7 else 'normal')
  59 
  60 # 遮罩上三角为白色
  61 for i in range(n):
  62     for j in range(i + 1, n):
  63         ax_heat.add_patch(plt.Rectangle((j - 0.5, i - 0.5), 1, 1, fill=True,
  64                                          facecolor='white', edgecolor='white', zorder=2))
  65 
  66 fig.colorbar(im, ax=ax_heat, shrink=0.6, label='相关系数', pad=0.08)
  67 fig.tight_layout()
  68 save_fig(fig, 'figures/fig_heatmap.pdf')