1 import numpy as np, matplotlib.pyplot as plt
   2 from scipy.stats import gaussian_kde
   3 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS
   4 setup_style()
   5 np.random.seed(42)
   6 
   7 years = np.arange(2010, 2024)
   8 cx = np.cumsum(np.random.normal(0.1, 0.3, len(years))) + 116.4
   9 cy = np.cumsum(np.random.normal(-0.05, 0.2, len(years))) + 39.9
  10 
  11 fig, ax = plt.subplots(figsize=(7, 6))
  12 ax.grid(True, linestyle='--', alpha=0.15); ax.set_axisbelow(True)
  13 
  14 # KDE 热力背景
  15 kde = gaussian_kde(np.vstack([cx, cy]))
  16 xg = np.linspace(cx.min()-0.5, cx.max()+0.5, 80)
  17 yg = np.linspace(cy.min()-0.5, cy.max()+0.5, 80)
  18 Xg, Yg = np.meshgrid(xg, yg)
  19 Zg = kde(np.vstack([Xg.ravel(), Yg.ravel()])).reshape(Xg.shape)
  20 ax.contourf(Xg, Yg, Zg, levels=8, cmap='Blues', alpha=0.15, zorder=0)
  21 
  22 # 轨迹线(带箭头)
  23 for i in range(len(years)-1):
  24     alpha = 0.3 + 0.7 * i / (len(years)-1)
  25     ax.annotate('', xy=(cx[i+1], cy[i+1]), xytext=(cx[i], cy[i]),
  26                 arrowprops=dict(arrowstyle='->', color=PALETTE[0], lw=1.5, alpha=alpha))
  27 
  28 # 起止点
  29 ax.scatter(cx[0], cy[0], s=120, color=COLORS['up'], edgecolor='white', linewidth=2, zorder=5, label=f'起点 ({years[0]})')
  30 ax.scatter(cx[-1], cy[-1], s=120, color=COLORS['down'], edgecolor='white', linewidth=2, zorder=5, marker='*', label=f'终点 ({years[-1]})')
  31 
  32 # 时间标注(只标注首尾和中间几个)
  33 for i in [0, len(years)//3, 2*len(years)//3, len(years)-1]:
  34     ax.text(cx[i]+0.05, cy[i]+0.05, str(years[i]), fontsize=8, fontweight='bold',
  35             bbox=dict(facecolor='white', alpha=0.7, edgecolor='none', pad=1))
  36 
  37 ax.set_xlabel('经度 (°E)', fontsize=11); ax.set_ylabel('纬度 (°N)', fontsize=11)
  38 ax.legend(frameon=False, labelspacing=0.35, handlelength=1.6, fontsize=9, loc='best')
  39 ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  40 fig.tight_layout()
  41 save_fig(fig, 'figures/fig_centroid_migration.pdf')