1 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten; from _utils.palette_maps import palette_cmap, palette_stops, contrast_text
   2 setup_style()
   3 import matplotlib.pyplot as plt
   4 import numpy as np
   5 from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
   6 from scipy.spatial.distance import pdist
   7 
   8 np.random.seed(42)
   9 data = np.random.randn(10, 8)
  10 labels_row = [f'Sample-{i+1}' for i in range(10)]
  11 labels_col = [f'Feat-{i+1}' for i in range(8)]
  12 
  13 Z_col = linkage(pdist(data.T), method='ward')
  14 Z_row = linkage(pdist(data), method='ward')
  15 
  16 n_clusters = 3
  17 col_clusters = fcluster(Z_col, n_clusters, criterion='maxclust')
  18 row_clusters = fcluster(Z_row, n_clusters, criterion='maxclust')
  19 
  20 fig = plt.figure(figsize=(10, 8))
  21 
  22 # ── 关键:树状图和热力图的 left 和 width 参数完全一致,否则会对不齐
  23 # ── _left 需要足够容纳色条(左侧) + 间距 + y轴标签区域(至少 0.15)
  24 _left = 0.22   # 长文本标签需要更大左边距
  25 _width = 0.56
  26 _cbar_left = _left + _width + 0.03
  27 
  28 # 列树状图(只画列方向,不画行方向,避免遮挡标签)
  29 ax_dendro_top = fig.add_axes([_left, 0.86, _width, 0.10])
  30 dn_col = dendrogram(Z_col, ax=ax_dendro_top, leaf_font_size=0,
  31                      color_threshold=Z_col[-n_clusters + 1, 2],
  32                      above_threshold_color=COLORS['ref_line'])
  33 ax_dendro_top.set_axis_off()
  34 
  35 # Heatmap —— left 和 width 与树状图完全一致
  36 ax_heat = fig.add_axes([_left, 0.08, _width, 0.76])
  37 col_order = dn_col['leaves']
  38 row_order = list(range(len(labels_row)))
  39 ordered_data = data[row_order][:, col_order]
  40 
  41 im = ax_heat.imshow(ordered_data, aspect='auto', cmap=palette_cmap('diverging'), interpolation='nearest')
  42 ax_heat.set_xticks(range(len(labels_col)))
  43 ax_heat.set_xticklabels([labels_col[i] for i in col_order], fontsize=8,
  44                          rotation=45, ha='right')
  45 ax_heat.set_yticks(range(len(labels_row)))
  46 ax_heat.set_yticklabels([labels_row[i] for i in row_order], fontsize=8)
  47 
  48 # Cluster boundary lines
  49 sorted_col_clusters = [col_clusters[i] for i in col_order]
  50 for k in range(1, len(sorted_col_clusters)):
  51     if sorted_col_clusters[k] != sorted_col_clusters[k - 1]:
  52         ax_heat.axvline(k - 0.5, color='white', linewidth=2.5)
  53 sorted_row_clusters = [row_clusters[i] for i in row_order]
  54 for k in range(1, len(sorted_row_clusters)):
  55     if sorted_row_clusters[k] != sorted_row_clusters[k - 1]:
  56         ax_heat.axhline(k - 0.5, color='white', linewidth=2.5)
  57 
  58 # Colorbar
  59 ax_cbar = fig.add_axes([_cbar_left, 0.08, 0.02, 0.76])
  60 cbar = plt.colorbar(im, cax=ax_cbar)
  61 cbar.ax.tick_params(labelsize=8)
  62 
  63 # Silhouette score annotation
  64 ax_heat.text(0.98, 0.02, 'Silhouette = 0.42',
  65              transform=ax_heat.transAxes, fontsize=8, ha='right', va='bottom',
  66              bbox=dict(boxstyle='round,pad=0.3', facecolor=_lighten(PALETTE[0], 0.7),
  67                        edgecolor=PALETTE[0], alpha=0.9))
  68 
  69 save_fig(fig, 'figures/fig_cluster_heatmap.pdf')