1 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
   2 setup_style()
   3 import matplotlib.pyplot as plt
   4 import matplotlib.gridspec as gridspec
   5 import numpy as np
   6 
   7 np.random.seed(42)
   8 t_treat = np.sort(np.random.exponential(20, 50))
   9 t_ctrl = np.sort(np.random.exponential(12, 50))
  10 
  11 def km_curve_data(times):
  12     n = len(times)
  13     surv = np.ones(n + 1)
  14     t_plot = np.zeros(n + 1)
  15     for i, t in enumerate(times):
  16         surv[i + 1] = surv[i] * (n - i - 1) / (n - i)
  17         t_plot[i + 1] = t
  18     return t_plot, surv
  19 
  20 def number_at_risk(times, time_points):
  21     return [np.sum(times >= tp) for tp in time_points]
  22 
  23 fig = plt.figure(figsize=(8, 6))
  24 gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1], hspace=0.08)
  25 ax = fig.add_subplot(gs[0])
  26 ax_risk = fig.add_subplot(gs[1])
  27 
  28 # Subtle grid
  29 ax.grid(alpha=0.15, linestyle='-', color=COLORS['grid'])
  30 ax.set_axisbelow(True)
  31 
  32 # Treatment group
  33 t1, s1 = km_curve_data(t_treat)
  34 ax.step(t1, s1, where='post', color=PALETTE[0], linewidth=2.5, label='Treatment (n=50)')
  35 # Gradient CI band
  36 ci_upper = np.clip(s1 + 0.08 * np.sqrt(np.linspace(1, 0.1, len(s1))), 0, 1)
  37 ci_lower = np.clip(s1 - 0.08 * np.sqrt(np.linspace(1, 0.1, len(s1))), 0, 1)
  38 ax.fill_between(t1, ci_lower, ci_upper, step='post', alpha=0.12, color=PALETTE[0])
  39 
  40 # Control group
  41 t2, s2 = km_curve_data(t_ctrl)
  42 ax.step(t2, s2, where='post', color=PALETTE[3], linewidth=2.5, label='Control (n=50)')
  43 ci_upper2 = np.clip(s2 + 0.10 * np.sqrt(np.linspace(1, 0.1, len(s2))), 0, 1)
  44 ci_lower2 = np.clip(s2 - 0.10 * np.sqrt(np.linspace(1, 0.1, len(s2))), 0, 1)
  45 ax.fill_between(t2, ci_lower2, ci_upper2, step='post', alpha=0.12, color=PALETTE[3])
  46 
  47 # Median survival markers with dashed lines
  48 def find_median_survival(t_arr, s_arr):
  49     for i in range(len(s_arr) - 1):
  50         if s_arr[i] >= 0.5 and s_arr[i + 1] < 0.5:
  51             return t_arr[i + 1]
  52     return None
  53 
  54 med_treat = find_median_survival(t1, s1)
  55 med_ctrl = find_median_survival(t2, s2)
  56 
  57 if med_treat is not None:
  58     ax.plot([med_treat, med_treat], [0, 0.5], '--', color=PALETTE[0], linewidth=1.0, alpha=0.7)
  59     ax.plot([0, med_treat], [0.5, 0.5], '--', color=PALETTE[0], linewidth=1.0, alpha=0.7)
  60     ax.scatter([med_treat], [0.5], color=PALETTE[0], s=60, zorder=5, marker='D',
  61                edgecolors='white', linewidths=1.0)
  62     ax.annotate(f'Median = {med_treat:.1f}m', xy=(med_treat, 0.5),
  63                 xytext=(med_treat + 3, 0.58), fontsize=8, color=PALETTE[0],
  64                 arrowprops=dict(arrowstyle='->', color=PALETTE[0], lw=0.8),
  65                 bbox=dict(boxstyle='round,pad=0.2', facecolor='white', alpha=0.8))
  66 
  67 if med_ctrl is not None:
  68     ax.plot([med_ctrl, med_ctrl], [0, 0.5], '--', color=PALETTE[3], linewidth=1.0, alpha=0.7)
  69     ax.plot([0, med_ctrl], [0.5, 0.5], '--', color=PALETTE[3], linewidth=1.0, alpha=0.7)
  70     ax.scatter([med_ctrl], [0.5], color=PALETTE[3], s=60, zorder=5, marker='D',
  71                edgecolors='white', linewidths=1.0)
  72     ax.annotate(f'Median = {med_ctrl:.1f}m', xy=(med_ctrl, 0.5),
  73                 xytext=(med_ctrl + 3, 0.42), fontsize=8, color=PALETTE[3],
  74                 arrowprops=dict(arrowstyle='->', color=PALETTE[3], lw=0.8),
  75                 bbox=dict(boxstyle='round,pad=0.2', facecolor='white', alpha=0.8))
  76 
  77 # Log-rank p-value annotation
  78 ax.annotate('Log-rank p = 0.003',
  79             xy=(0.98, 0.98), xycoords='axes fraction', ha='right', va='top',
  80             fontsize=9, fontweight='bold',
  81             bbox=dict(boxstyle='round,pad=0.4', facecolor=_lighten(PALETTE[0], 0.7),
  82                       edgecolor=PALETTE[0], alpha=0.9))
  83 
  84 ax.set_ylabel('Survival probability', fontsize=11)
  85 ax.set_ylim(0, 1.05)
  86 ax.set_xlim(left=0)
  87 ax.legend(frameon=False, labelspacing=0.35, handlelength=1.6, fontsize=9, loc='best')
  88 ax.spines['top'].set_visible(False)
  89 ax.spines['right'].set_visible(False)
  90 ax.set_xticklabels([])
  91 
  92 # Number-at-risk table
  93 time_points = np.arange(0, max(t_treat.max(), t_ctrl.max()) + 5, 10)
  94 nar_treat = number_at_risk(t_treat, time_points)
  95 nar_ctrl = number_at_risk(t_ctrl, time_points)
  96 
  97 ax_risk.set_xlim(ax.get_xlim())
  98 ax_risk.set_ylim(-0.5, 1.5)
  99 for i, tp in enumerate(time_points):
 100     ax_risk.text(tp, 1, str(nar_treat[i]), ha='center', va='center',
 101                  fontsize=8, color=PALETTE[0], fontweight='bold')
 102     ax_risk.text(tp, 0, str(nar_ctrl[i]), ha='center', va='center',
 103                  fontsize=8, color=PALETTE[3], fontweight='bold')
 104 ax_risk.text(-2, 1, 'Treatment', ha='right', va='center', fontsize=8,
 105              color=PALETTE[0], fontweight='bold')
 106 ax_risk.text(-2, 0, 'Control', ha='right', va='center', fontsize=8,
 107              color=PALETTE[3], fontweight='bold')
 108 ax_risk.set_xlabel('Time (months)', fontsize=11)
 109 ax_risk.set_yticks([])
 110 ax_risk.spines['top'].set_visible(False)
 111 ax_risk.spines['right'].set_visible(False)
 112 ax_risk.spines['left'].set_visible(False)
 113 ax_risk.set_title('Number at risk', fontsize=8, loc='left', fontstyle='italic')
 114 
 115 fig.tight_layout()
 116 save_fig(fig, 'figures/fig_kaplan_meier.pdf')