1 import numpy as np 2 import matplotlib.pyplot as plt 3 from scipy.ndimage import gaussian_filter1d 4 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten 5 6 setup_style() 7 np.random.seed(42) 8 9 # === 模拟 5 个类别在 50 个时间点的数值 === 10 n_t = 50; n_cat = 5 11 t = np.arange(n_t) 12 # 每个类别有不同的生命周期形状 13 shapes = [ 14 20 + 30 * np.exp(-((t - 20)**2) / 250), # 凸起在中间 15 10 + 15 * (1 / (1 + np.exp(-0.2 * (t - 25)))), # 后期增长 16 25 - 20 * (1 / (1 + np.exp(-0.2 * (t - 15)))) + 5, # 早期衰退 17 18 * np.sin(t * 0.3) ** 2 + 5, # 周期波动 18 12 + np.random.normal(0, 2, n_t) # 平稳基线 19 ] 20 data = np.array([gaussian_filter1d(s, sigma=2) for s in shapes]) 21 data = np.clip(data, 0.5, None) # 保证非负 22 23 # === 居中基线:每个时刻总值除以 2,作为偏移 === 24 total = data.sum(axis=0) 25 baseline = -total / 2 # 起点放底,向上堆叠 26 fig, ax = plt.subplots(figsize=(9, 4.5)) 27 28 names = ['类别 A', '类别 B', '类别 C', '类别 D', '类别 E'] 29 cumsum = baseline.copy() 30 for i, (vals, name) in enumerate(zip(data, names)): 31 color = PALETTE[i % len(PALETTE)] 32 ax.fill_between(t, cumsum, cumsum + vals, 33 color=_lighten(color, 0.25), alpha=0.88, 34 edgecolor=color, linewidth=0.5, label=name) 35 # ★ 末端标签:放在每条流带末端的中心 36 end_mid = cumsum[-1] + vals[-1] / 2 37 ax.text(t[-1] + 0.7, end_mid, name, fontsize=8, va='center', 38 color=color, fontweight='bold', 39 bbox=dict(boxstyle='round,pad=0.18', facecolor='white', 40 edgecolor=color, alpha=0.9, linewidth=0.5)) 41 cumsum += vals 42 43 # 中心参考线 44 ax.axhline(0, color=COLORS['ref_line'], linewidth=0.5, alpha=0.4, linestyle='-') 45 46 ax.set_xlabel('时间', fontsize=10) 47 ax.set_yticks([]) # 居中堆叠图通常省略 y 轴刻度(数值由颜色面积表达) 48 ax.set_xlim(t[0], t[-1] + 7) 49 for sp in ['top', 'right', 'left']: ax.spines[sp].set_visible(False) 50 ax.tick_params(axis='y', length=0) 51 ax.grid(axis='x', alpha=0.08, linestyle='--', color=COLORS['grid']) 52 53 # 顶部小注释解释读法 54 ax.text(0.02, 0.97, '流带厚度 = 该时刻的数值;垂直位置无意义', 55 transform=ax.transAxes, fontsize=7, color=COLORS['text'], 56 style='italic', va='top', 57 bbox=dict(boxstyle='round,pad=0.2', facecolor='white', 58 edgecolor=COLORS['grid'], alpha=0.85, linewidth=0.3)) 59 60 fig.tight_layout() 61 save_fig(fig, 'figures/fig_streamgraph.pdf')