1 import numpy as np
   2 import matplotlib.pyplot as plt
   3 from scipy.stats import gaussian_kde
   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 = ['组A', '组B', '组C', '组D']
  10 data = [np.random.normal(loc, s, 80) for loc, s in [(80, 5), (85, 3), (78, 8), (90, 4)]]
  11 
  12 # ★ 自适应高度
  13 _fig_h = max(4, len(groups) * 1.2 + 1)
  14 fig, ax = plt.subplots(figsize=(8, _fig_h))
  15 
  16 for i, (name, d) in enumerate(zip(groups, data)):
  17     pos = i
  18 
  19     # 渐变半小提琴(右侧)
  20     kde = gaussian_kde(d, bw_method=0.3)
  21     yr = np.linspace(d.min() - 4, d.max() + 4, 300)
  22     density = kde(yr)
  23     density_norm = density / density.max() * 0.35
  24 
  25     for layer in range(6):
  26         frac = layer / 6
  27         alpha = 0.35 - frac * 0.05
  28         ax.fill_betweenx(yr, pos + frac * 0.02, pos + density_norm * (1 - frac * 0.12),
  29                          alpha=alpha, color=PALETTE[i], linewidth=0)
  30     # 原色边框轮廓
  31     ax.plot(pos + density_norm, yr, color=PALETTE[i], linewidth=1.2, alpha=0.8)
  32 
  33     # 箱线图(左侧,窄)
  34     bp = ax.boxplot(d, positions=[pos - 0.18], widths=0.12, vert=True, patch_artist=True,
  35                     boxprops=dict(facecolor=_lighten(PALETTE[i], 0.4),
  36                                   edgecolor=PALETTE[i], linewidth=1.2),
  37                     medianprops=dict(color=COLORS['text'], linewidth=1.8),
  38                     whiskerprops=dict(linewidth=1, color=PALETTE[i]),
  39                     capprops=dict(linewidth=1, color=COLORS['ref_line']),
  40                     flierprops=dict(marker='', markersize=0))
  41 
  42     # 抖动散点(最左侧)
  43     jitter = np.random.uniform(-0.08, 0.08, len(d))
  44     ax.scatter(pos - 0.38 + jitter, d, s=6, alpha=0.2, color=PALETTE[i], edgecolor='none')
  45 
  46     # 均值菱形
  47     ax.scatter(pos - 0.18, d.mean(), marker='D', s=45, color=PALETTE[i],
  48                edgecolor='white', linewidth=1.2, zorder=5)
  49 
  50     # 均值数值标注
  51     ax.text(pos - 0.32, d.mean(), f'{d.mean():.1f}', fontsize=7, color=PALETTE[i],
  52             ha='right', va='center', fontweight='bold',
  53             bbox=dict(boxstyle='round,pad=0.15', facecolor='white',
  54                       edgecolor='none', alpha=0.7))
  55 
  56 ax.set_xticks(range(len(groups)))
  57 ax.set_xticklabels(groups, fontsize=10)
  58 ax.set_ylabel('数值', fontsize=11)
  59 ax.spines['top'].set_visible(False)
  60 ax.spines['right'].set_visible(False)
  61 ax.grid(axis='y', alpha=0.12, linestyle='--', color=COLORS['grid'])
  62 fig.tight_layout()
  63 save_fig(fig, 'figures/fig_raincloud.pdf')