1 import numpy as np, matplotlib.pyplot as plt
   2 from scipy.stats import gaussian_kde, shapiro
   3 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
   4 setup_style()
   5 
   6 np.random.seed(42)
   7 groups = ['Group A', 'Group B', 'Group C']
   8 data_all = [np.random.lognormal(2, 0.8, 300), np.random.lognormal(2.2, 0.6, 300),
   9             np.random.lognormal(1.8, 1.0, 300)]
  10 
  11 # ★ 自适应高度
  12 _fig_h = max(4, len(groups) * 1.5 + 1)
  13 fig, ax = plt.subplots(figsize=(10, _fig_h))
  14 for i, (grp, data) in enumerate(zip(groups, data_all)):
  15     y_center = i * 2.5
  16     kde = gaussian_kde(data)
  17     x_kde = np.linspace(data.min()*0.8, np.percentile(data, 99), 200)
  18     y_kde = kde(x_kde)
  19     y_kde_norm = y_kde / y_kde.max() * 0.8
  20 
  21     n_layers = 15
  22     for k in range(n_layers, 0, -1):
  23         frac = k / n_layers
  24         ax.fill_between(x_kde, y_center, y_center + y_kde_norm*frac,
  25                         alpha=0.035, color=PALETTE[i], linewidth=0)
  26     ax.fill_between(x_kde, y_center, y_center + y_kde_norm, alpha=0.2, color=PALETTE[i], linewidth=0)
  27     ax.plot(x_kde, y_center + y_kde_norm, color=PALETTE[i], linewidth=1.5)
  28 
  29     ax.boxplot([data], positions=[y_center], vert=False, widths=0.3, patch_artist=True,
  30                boxprops=dict(facecolor=_lighten(PALETTE[i], 0.4), edgecolor=PALETTE[i], linewidth=1.2),
  31                medianprops=dict(color=COLORS['text'], linewidth=1.5),
  32                whiskerprops=dict(color=PALETTE[i], linewidth=1),
  33                capprops=dict(color=PALETTE[i], linewidth=1),
  34                flierprops=dict(marker='.', markersize=2, alpha=0.3, markerfacecolor=PALETTE[i]))
  35 
  36     jitter = np.random.uniform(-0.15, -0.55, len(data))
  37     ax.scatter(data[::3], y_center + jitter[:len(data[::3])], s=4, alpha=0.25, color=PALETTE[i], zorder=2)
  38 
  39     for pct, pct_label in [(25, 'Q1'), (50, 'Median'), (75, 'Q3')]:
  40         pv = np.percentile(data, pct)
  41         ax.plot(pv, y_center - 0.7, '|', color=PALETTE[i], markersize=8, markeredgewidth=1.5, zorder=4)
  42         ax.text(pv, y_center - 0.9, f'{pct_label}\n{pv:.1f}', ha='center', va='top', fontsize=7, color=COLORS['text'])
  43 
  44     stat, p = shapiro(data[:50])
  45     ax.text(np.percentile(data, 99)*1.02, y_center + 0.3, f'W={stat:.3f}, p={p:.3f}',
  46             fontsize=7.5, color=COLORS['text'], va='center',
  47             bbox=dict(boxstyle='round,pad=0.25', facecolor=COLORS['bg_box'], edgecolor=COLORS['grid'], alpha=0.9))
  48 
  49 ax.set_yticks([i*2.5 for i in range(len(groups))]); ax.set_yticklabels(groups, fontsize=10)
  50 ax.set_xlabel('Value', fontsize=11); ax.grid(axis='x', alpha=0.15, linestyle='--')
  51 ax.spines['top'].set_visible(False)
  52 ax.spines['right'].set_visible(False)
  53 fig.tight_layout()
  54 save_fig(fig, 'figures/fig_dist.pdf')