1 import numpy as np 2 import matplotlib.pyplot as plt 3 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten, smart_labels 4 setup_style() 5 6 methods = ['Ours (full)', 'w/o Attention', 'w/o Pretrain', 'w/o Augment', 7 'Baseline-A', 'Baseline-B', 'Baseline-C'] 8 deltas = [+5.2, +3.1, +1.8, +0.5, 0.0, -1.3, -2.7] 9 10 # ── 自适应高度 11 _fig_h = max(4, len(methods) * 0.7 + 1) 12 fig, ax = plt.subplots(figsize=(8, _fig_h)) 13 y_pos = np.arange(len(methods)) 14 15 # 方向性颜色背景 16 ax.axvspan(0, max(deltas)*1.3, alpha=0.05, color=COLORS['up'], zorder=0) 17 ax.axvspan(min(deltas)*1.3, 0, alpha=0.05, color=COLORS['down'], zorder=0) 18 19 # Color: positive = up(green), negative = down(red) 20 base_colors = [COLORS['up'] if d >= 0 else COLORS['down'] for d in deltas] 21 22 # 柱体阴影 23 ax.barh(y_pos + 0.03, deltas, height=0.5, color='#cccccc', alpha=0.1, zorder=1) 24 # ── 主柱体:浅色填充 + 原色边框 25 bars = ax.barh(y_pos, deltas, height=0.5, 26 color=[_lighten(c, 0.4) for c in base_colors], 27 edgecolor=base_colors, linewidth=1.5, zorder=3) 28 29 # Zero reference line 30 ax.axvline(0, color=COLORS['text'], linewidth=1.2, zorder=2) 31 32 # Value labels at bar ends(白底保护) 33 for i, (bar, d) in enumerate(zip(bars, deltas)): 34 x_pos = d + (0.2 if d >= 0 else -0.2) 35 ha = 'left' if d >= 0 else 'right' 36 sign = '+' if d > 0 else '' 37 ax.text(x_pos, y_pos[i], f'{sign}{d:.1f}%', va='center', ha=ha, 38 fontsize=9, fontweight='bold', color=base_colors[i], 39 bbox=dict(boxstyle='round,pad=0.1', facecolor='white', edgecolor='none', alpha=0.7)) 40 41 # Highlight "Ours" row 42 ax.axhspan(y_pos[0]-0.35, y_pos[0]+0.35, alpha=0.06, color=PALETTE[0], zorder=0) 43 bars[0].set_edgecolor(PALETTE[0]); bars[0].set_linewidth(2.0) 44 45 # 方向标注 46 ax.text(0.98, 0.02, '更优 →', transform=ax.transAxes, fontsize=8, ha='right', 47 color=COLORS['up'], fontweight='bold') 48 ax.text(0.02, 0.02, '← 更差', transform=ax.transAxes, fontsize=8, ha='left', 49 color=COLORS['down'], fontweight='bold') 50 51 ax.set_yticks(y_pos) 52 ax.set_yticklabels(methods, fontsize=10) 53 ax.set_xlabel('Relative Improvement over Baseline (%)', fontsize=11) 54 ax.invert_yaxis() 55 ax.grid(axis='x', alpha=0.12, linestyle='--', color=COLORS['grid']) 56 ax.spines['left'].set_visible(False) 57 ax.spines['top'].set_visible(False) 58 ax.spines['right'].set_visible(False) 59 fig.tight_layout() 60 save_fig(fig, 'figures/fig_diverging_bar.pdf')