1 import numpy as np
   2 import matplotlib.pyplot as plt
   3 from scipy.stats import gaussian_kde, ttest_ind
   4 import matplotlib.colors as mcolors
   5 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
   6 setup_style()
   7 
   8 np.random.seed(42)
   9 groups = ['Ours', 'Method A', 'Method B']
  10 data = [np.random.normal(92, 3, 100), np.random.normal(88, 4, 100),
  11         np.random.normal(85, 5, 100)]
  12 
  13 def cohens_d(g1, g2):
  14     n1, n2 = len(g1), len(g2)
  15     pooled_std = np.sqrt(((n1 - 1) * g1.std() ** 2 + (n2 - 1) * g2.std() ** 2) / (n1 + n2 - 2))
  16     return (g1.mean() - g2.mean()) / pooled_std
  17 
  18 # ★ 自适应高度
  19 _fig_h = max(4, len(groups) * 1.0 + 1)
  20 fig, ax = plt.subplots(figsize=(8, _fig_h))
  21 for i, (name, d) in enumerate(zip(groups, data)):
  22     pos = i
  23     # Gradient half-violin (right side)
  24     kde = gaussian_kde(d, bw_method=0.3)
  25     yr = np.linspace(d.min() - 4, d.max() + 4, 300)
  26     density = kde(yr)
  27     density_norm = density / density.max() * 0.38
  28     base_rgb = mcolors.to_rgb(PALETTE[i])
  29     for layer in range(6):
  30         frac = layer / 6
  31         alpha = 0.35 - frac * 0.05
  32         ax.fill_betweenx(yr, pos + frac * 0.02, pos + density_norm * (1 - frac * 0.12),
  33                          alpha=alpha, color=PALETTE[i], linewidth=0)
  34     ax.plot(pos + density_norm, yr, color=PALETTE[i], linewidth=1.2, alpha=0.8)
  35 
  36     # Box plot (left, narrow)
  37     bp = ax.boxplot(d, positions=[pos - 0.18], widths=0.12, vert=True, patch_artist=True,
  38                     boxprops=dict(facecolor=_lighten(PALETTE[i], 0.4),
  39                                   edgecolor=PALETTE[i], linewidth=1.2),
  40                     medianprops=dict(color=COLORS['text'], linewidth=1.8),
  41                     whiskerprops=dict(linewidth=1, color=PALETTE[i]),
  42                     capprops=dict(linewidth=1, color=COLORS['ref_line']),
  43                     flierprops=dict(marker='', markersize=0))
  44 
  45     # Jittered strip (far left)
  46     jitter = np.random.uniform(-0.08, 0.08, len(d))
  47     ax.scatter(pos - 0.38 + jitter, d, s=6, alpha=0.2, color=PALETTE[i], edgecolor='none')
  48 
  49     # Mean diamond
  50     ax.scatter(pos - 0.18, d.mean(), marker='D', s=45, color=PALETTE[i],
  51                edgecolor='white', linewidth=1.2, zorder=5)
  52 
  53 # Significance brackets with p-values and Cohen's d
  54 def add_bracket(ax, x1, x2, y, p_val, d_val, h=1.5):
  55     ax.plot([x1, x1, x2, x2], [y, y + h, y + h, y], color=COLORS['text'], linewidth=0.8)
  56     stars = '***' if p_val < 0.001 else '**' if p_val < 0.01 else '*' if p_val < 0.05 else 'n.s.'
  57     ax.text((x1 + x2) / 2, y + h + 0.2, f'{stars} (p={p_val:.1e})\nd={d_val:.2f}',
  58             ha='center', va='bottom', fontsize=7, color=COLORS['text'],
  59             bbox=dict(boxstyle='round,pad=0.2', facecolor=COLORS['bg_box'],
  60                       edgecolor=COLORS['grid'], alpha=0.9, linewidth=0.3))
  61 
  62 y_max = max(d.max() for d in data) + 2
  63 for idx, (g1, g2) in enumerate([(0, 1), (0, 2)]):
  64     _, p = ttest_ind(data[g1], data[g2])
  65     d_val = cohens_d(data[g1], data[g2])
  66     add_bracket(ax, g1, g2, y_max + idx * 7, p, d_val)
  67 
  68 ax.set_xticks(range(len(groups)))
  69 ax.set_xticklabels(groups, fontsize=10)
  70 ax.set_ylabel('Accuracy (%)', fontsize=11)
  71 ax.spines['top'].set_visible(False)
  72 ax.spines['right'].set_visible(False)
  73 ax.grid(axis='y', alpha=0.15, linestyle='--')
  74 fig.tight_layout()
  75 save_fig(fig, 'figures/fig_raincloud.pdf')