1 import numpy as np
   2 import matplotlib.pyplot as plt
   3 from scipy.stats import ttest_ind
   4 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
   5 setup_style()
   6 
   7 np.random.seed(42)
   8 groups = ['A组', 'B组', 'C组', 'D组']
   9 data = [np.random.normal(m, s, 100) for m, s in [(80, 5), (85, 3), (78, 8), (90, 4)]]
  10 
  11 fig, ax = plt.subplots(figsize=(8, 5.5))
  12 
  13 # ★ 淡色填充 + 原色边框小提琴
  14 parts = ax.violinplot(data, positions=range(len(groups)), showmeans=False,
  15                       showmedians=False, showextrema=False)
  16 
  17 for i, pc in enumerate(parts['bodies']):
  18     pc.set_facecolor(_lighten(PALETTE[i], 0.4))
  19     pc.set_edgecolor(PALETTE[i])
  20     pc.set_linewidth(1.2)
  21     pc.set_alpha(0.7)
  22 
  23 # 叠加窄箱线图
  24 bp = ax.boxplot(data, positions=range(len(groups)), widths=0.15, patch_artist=True,
  25                 boxprops=dict(facecolor='white', edgecolor=COLORS['text'], linewidth=1.2),
  26                 medianprops=dict(color=COLORS['text'], linewidth=2),
  27                 whiskerprops=dict(linewidth=1.2),
  28                 capprops=dict(linewidth=1.2),
  29                 flierprops=dict(marker='.', markersize=3, alpha=0.3))
  30 
  31 # 均值菱形 + 数值标注
  32 for i, d in enumerate(data):
  33     ax.scatter(i, d.mean(), marker='D', s=40, color=PALETTE[i],
  34                edgecolor='white', linewidth=1, zorder=5)
  35     ax.text(i + 0.25, d.mean(), f'{d.mean():.1f}', fontsize=7.5, color=PALETTE[i],
  36             va='center', fontweight='bold',
  37             bbox=dict(boxstyle='round,pad=0.1', facecolor='white',
  38                       edgecolor='none', alpha=0.7))
  39 
  40 # 显著性括号
  41 def add_significance(ax, x1, x2, y, p_val, h=2):
  42     ax.plot([x1, x1, x2, x2], [y, y + h, y + h, y], color=COLORS['text'], linewidth=0.8)
  43     stars = '***' if p_val < 0.001 else '**' if p_val < 0.01 else '*' if p_val < 0.05 else 'n.s.'
  44     ax.text((x1 + x2) / 2, y + h + 0.3, f'{stars}\np={p_val:.2e}',
  45             ha='center', va='bottom', fontsize=7, color=COLORS['text'],
  46             bbox=dict(boxstyle='round,pad=0.15', facecolor=COLORS['bg_box'],
  47                       edgecolor=COLORS['grid'], alpha=0.9, linewidth=0.3))
  48 
  49 y_max = max(d.max() for d in data) + 3
  50 # 比较最优组(D组)与其他组
  51 for idx, comp in enumerate([0, 1, 2]):
  52     _, p = ttest_ind(data[3], data[comp])
  53     add_significance(ax, comp, 3, y_max + idx * 6, p)
  54 
  55 ax.set_xticks(range(len(groups)))
  56 ax.set_xticklabels(groups, fontsize=10)
  57 ax.set_ylabel('数值', fontsize=11)
  58 ax.spines['top'].set_visible(False)
  59 ax.spines['right'].set_visible(False)
  60 ax.grid(axis='y', alpha=0.12, linestyle='--', color=COLORS['grid'])
  61 fig.tight_layout()
  62 save_fig(fig, 'figures/fig_violin.pdf')