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.patches as mpatches
   5 import numpy as np
   6 
   7 labels = ['Baseline', '+Attention', '+Augment', '+Pretrain', '-Dropout']
   8 deltas = [0.82,        0.04,          0.02,       0.05,       -0.01]
   9 
  10 cum = [deltas[0]]
  11 for d in deltas[1:]:
  12     cum.append(cum[-1] + d)
  13 final_val = cum[-1]
  14 total_delta = final_val - deltas[0]
  15 
  16 layer_colors = [COLORS['up'] if d >= 0 else COLORS['down'] for d in deltas[1:]]
  17 n = len(labels)
  18 
  19 fig, ax = plt.subplots(figsize=(9, 5))
  20 ax.grid(axis='y', alpha=0.12, linestyle='-', color=COLORS['grid'])
  21 ax.set_axisbelow(True)
  22 
  23 x_positions = np.arange(n)
  24 
  25 # ── 色带层叠(每步增量的层带位置,延伸到最右边)
  26 for i in range(1, n):
  27     c = layer_colors[i - 1]
  28     bottom = min(cum[i-1], cum[i])
  29     top = max(cum[i-1], cum[i])
  30     ax.fill_between([x_positions[i] - 0.5, x_positions[-1] + 0.5], bottom, top,
  31                     alpha=0.15, color=c, zorder=1 + i)
  32     ax.plot([x_positions[i] - 0.5, x_positions[-1] + 0.5], [cum[i], cum[i]],
  33             color=c, linewidth=0.7, linestyle='--', alpha=0.35, zorder=1 + i)
  34 
  35 # Baseline 底层
  36 ax.fill_between([x_positions[0] - 0.5, x_positions[-1] + 0.5], 0, cum[0],
  37                 alpha=0.06, color=PALETTE[0], zorder=0)
  38 
  39 # ── 阶梯连线
  40 ax.step(x_positions, cum, where='mid', color=PALETTE[0], linewidth=2.8, zorder=10)
  41 
  42 # ── 圆点
  43 for i in range(n):
  44     c = PALETTE[0] if i == 0 else layer_colors[i - 1]
  45     ax.scatter(x_positions[i], cum[i], color=c, s=90, zorder=11,
  46                edgecolors='white', linewidths=2.0)
  47 
  48 # ── 数值标注 —— 所有步骤都标,统一放在圆点上方
  49 for i in range(n):
  50     c = PALETTE[0] if i == 0 else layer_colors[i - 1]
  51     ax.text(x_positions[i], cum[i] + 0.008, f'{cum[i]:.3f}', ha='center', va='bottom',
  52             fontsize=8.5, fontweight='bold' if (i == 0 or i == n-1) else 'normal',
  53             color=c,
  54             bbox=dict(boxstyle='round,pad=0.15', facecolor='white',
  55                       edgecolor=c if (i == 0 or i == n-1) else 'none',
  56                       alpha=0.9, linewidth=0.5), zorder=12)
  57 
  58 # ── 总增量标注(右上角)
  59 ax.text(0.97, 0.95, f'Total: +{total_delta:.2f} (+{total_delta/deltas[0]*100:.1f}%)',
  60         transform=ax.transAxes, fontsize=9.5, ha='right', va='top',
  61         fontweight='bold', color=COLORS['up'],
  62         bbox=dict(boxstyle='round,pad=0.4', facecolor='white',
  63                   edgecolor=COLORS['up'], alpha=0.9, linewidth=1.0), zorder=15)
  64 
  65 # ── 贡献图例(将贡献信息全部放在图例,而非图面上标)
  66 legend_patches = []
  67 for i in range(1, n):
  68     d = deltas[i]
  69     c = layer_colors[i - 1]
  70     sign = '+' if d >= 0 else ''
  71     pct = abs(d) / total_delta * 100
  72     patch = mpatches.Patch(facecolor=_lighten(c, 0.4), edgecolor=c, linewidth=1.2,
  73                            label=f'{labels[i]}  {sign}{d:.2f} ({pct:.0f}%)')
  74     legend_patches.append(patch)
  75 legend = ax.legend(handles=legend_patches, loc='lower right',
  76                    frameon=False, labelspacing=0.35, handlelength=1.6, fontsize=8.5,
  77                    facecolor='white', title='Contribution', title_fontsize=9,
  78                    handlelength=1.5, handleheight=1.0)
  79 legend.set_zorder(15)
  80 
  81 ax.set_xticks(x_positions)
  82 ax.set_xticklabels(labels, fontsize=10)
  83 ax.set_ylabel('Accuracy', fontsize=11)
  84 ax.set_xlim(-0.7, n - 0.3)
  85 ax.set_ylim(deltas[0] * 0.92, final_val * 1.12)
  86 ax.spines['top'].set_visible(False)
  87 ax.spines['right'].set_visible(False)
  88 fig.tight_layout()
  89 save_fig(fig, 'figures/fig_waterfall.pdf')