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.colors as mcolors 5 import numpy as np 6 7 np.random.seed(42) 8 method1 = np.random.normal(50, 10, 100) 9 method2 = method1 + np.random.normal(0.5, 3, 100) 10 mean_vals = (method1 + method2) / 2 11 diff_vals = method1 - method2 12 mean_diff = np.mean(diff_vals) 13 std_diff = np.std(diff_vals) 14 15 fig, ax = plt.subplots(figsize=(7, 5.5)) 16 17 # Subtle grid 18 ax.grid(alpha=0.15, linestyle='-', color=COLORS['grid']) 19 ax.set_axisbelow(True) 20 21 # Gradient CI band (fading from center outward) 22 x_range = np.linspace(mean_vals.min() - 2, mean_vals.max() + 2, 200) 23 upper = mean_diff + 1.96 * std_diff 24 lower = mean_diff - 1.96 * std_diff 25 # Inner band (darker) 26 ax.fill_between(x_range, mean_diff - 0.5 * std_diff, mean_diff + 0.5 * std_diff, 27 alpha=0.15, color=PALETTE[0], label='±0.5 SD') 28 # Middle band 29 ax.fill_between(x_range, mean_diff - 1.0 * std_diff, mean_diff + 1.0 * std_diff, 30 alpha=0.10, color=PALETTE[0]) 31 # Outer band (lightest) 32 ax.fill_between(x_range, lower, upper, alpha=0.06, color=PALETTE[3], label='±1.96 SD (95% CI)') 33 34 # Scatter points 35 ax.scatter(mean_vals, diff_vals, color=PALETTE[0], alpha=0.55, s=30, 36 edgecolors='white', linewidths=0.5, zorder=3) 37 38 # Mean line 39 ax.axhline(mean_diff, color=PALETTE[0], linestyle='-', linewidth=1.8, 40 label=f'Mean bias: {mean_diff:.2f}') 41 # Limits of agreement 42 ax.axhline(upper, color=PALETTE[3], linestyle='--', linewidth=1.2, 43 label=f'+1.96 SD: {upper:.2f}') 44 ax.axhline(lower, color=PALETTE[3], linestyle='--', linewidth=1.2, 45 label=f'-1.96 SD: {lower:.2f}') 46 47 # Proportional bias regression line 48 z = np.polyfit(mean_vals, diff_vals, 1) 49 p = np.poly1d(z) 50 x_fit = np.linspace(mean_vals.min(), mean_vals.max(), 100) 51 ax.plot(x_fit, p(x_fit), color=COLORS['highlight'], linewidth=1.5, linestyle='-.', 52 label=f'Prop. bias (slope={z[0]:.3f})', zorder=4) 53 54 # Outlier labels (points beyond ±1.96 SD) 55 outliers = np.where((diff_vals > upper) | (diff_vals < lower))[0] 56 for idx in outliers: 57 ax.annotate(f'#{idx}', xy=(mean_vals[idx], diff_vals[idx]), 58 xytext=(mean_vals[idx] + 1.5, diff_vals[idx] + 0.8), 59 fontsize=7, color=COLORS['down'], 60 arrowprops=dict(arrowstyle='->', color=COLORS['down'], lw=0.8), 61 bbox=dict(boxstyle='round,pad=0.3', facecolor='white', 62 edgecolor=COLORS['down'], alpha=0.9)) 63 64 ax.set_xlabel('Mean of two methods', fontsize=11) 65 ax.set_ylabel('Difference (Method 1 − Method 2)', fontsize=11) 66 ax.legend(frameon=False, labelspacing=0.35, handlelength=1.6, fontsize=7.5, loc='upper left', 67 fancybox=True) 68 ax.spines['top'].set_visible(False) 69 ax.spines['right'].set_visible(False) 70 fig.tight_layout() 71 save_fig(fig, 'figures/fig_bland_altman.pdf')