1 import numpy as np; from _utils.vivid_config import palette_colors
   2 import matplotlib.pyplot as plt
   3 from matplotlib.patches import Rectangle
   4 from matplotlib.colors import LinearSegmentedColormap
   5 from datetime import date, timedelta
   6 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
   7 
   8 setup_style(); scale_colors = palette_colors()
   9 np.random.seed(42)
  10 
  11 # === 模拟一年的日数据(周末偏低,月底偏高,几个事件峰值)===
  12 start = date(2024, 1, 1)
  13 n_days = 366
  14 daily = np.random.gamma(2.0, 1.2, n_days)  # 基线
  15 for i in range(n_days):
  16     d = start + timedelta(days=i)
  17     if d.weekday() >= 5: daily[i] *= 0.55  # 周末
  18     if d.day >= 28: daily[i] *= 1.3  # 月底
  19 # 几个事件峰值
  20 for ev in [40, 95, 180, 290]:
  21     daily[ev:ev+3] *= 2.5
  22 
  23 # === 转 7×53 矩阵:行=周中第几天(周一-周日),列=年中第几周 ===
  24 grid = np.full((7, 54), np.nan)
  25 month_starts = []  # 记录每月第一天位置(用于画分隔线)
  26 for i in range(n_days):
  27     d = start + timedelta(days=i)
  28     week = int(d.strftime('%W'))  # ISO 周
  29     weekday = d.weekday()  # 0=Mon
  30     grid[weekday, week] = daily[i]
  31     if d.day == 1:
  32         month_starts.append((d.month, week, weekday))
  33 
  34 # === 主色调渐变 colormap(用原色序首色的浅→深)===
  35 base = scale_colors[0]
  36 cmap_calendar = LinearSegmentedColormap.from_list(
  37     'cal', [_lighten(base, 0.92), _lighten(base, 0.5), base, _lighten(base, -0.15) if False else base],
  38     N=128
  39 )
  40 
  41 fig, ax = plt.subplots(figsize=(11, 2.6))
  42 im = ax.imshow(grid, aspect='equal', cmap=cmap_calendar, vmin=0,
  43                vmax=np.nanpercentile(grid, 98))
  44 
  45 # === 月份分隔线 + 月名标注 ===
  46 month_names = ['1月', '2月', '3月', '4月', '5月', '6月',
  47                '7月', '8月', '9月', '10月', '11月', '12月']
  48 for m, wk, _ in month_starts:
  49     ax.axvline(wk - 0.5, color=COLORS['grid'], linewidth=0.8, alpha=0.5)
  50     ax.text(wk + 0.5, -1.0, month_names[m - 1], fontsize=8,
  51             ha='left', va='center', color=COLORS['text'])
  52 
  53 # === Y 轴:仅显示 Mon / Wed / Fri ===
  54 ax.set_yticks([0, 2, 4, 6])
  55 ax.set_yticklabels(['周一', '周三', '周五', '周日'], fontsize=8)
  56 ax.set_xticks([])
  57 ax.tick_params(axis='y', length=0)
  58 for spine in ax.spines.values(): spine.set_visible(False)
  59 
  60 # === 顶部 colorbar(横向)===
  61 cbar = fig.colorbar(im, ax=ax, orientation='horizontal', shrink=0.35,
  62                     pad=0.25, aspect=30)
  63 cbar.set_label('日均值', fontsize=8)
  64 cbar.ax.tick_params(labelsize=7, length=0)
  65 cbar.outline.set_linewidth(0)
  66 
  67 # === 异常日(top 1%)标注 ===
  68 threshold = np.nanpercentile(daily, 99)
  69 outliers_idx = np.where(daily > threshold)[0]
  70 for idx in outliers_idx[:5]:  # 最多标 5 个
  71     d = start + timedelta(days=int(idx))
  72     wk = int(d.strftime('%W')); wd = d.weekday()
  73     ax.add_patch(Rectangle((wk - 0.45, wd - 0.45), 0.9, 0.9,
  74                             fill=False, edgecolor=COLORS['highlight'],
  75                             linewidth=1.3, zorder=5))
  76 
  77 fig.tight_layout()
  78 save_fig(fig, 'figures/fig_calendar_heatmap.pdf')