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 n = 2000 9 log2fc = np.random.normal(0, 1.5, n) 10 pvals = 10 ** (-np.abs(log2fc) * np.random.uniform(0.5, 3, n)) 11 neg_log_p = -np.log10(pvals) 12 gene_names = [f'Gene_{i}' for i in range(n)] 13 14 sig_up = (log2fc > 1) & (neg_log_p > 2) 15 sig_down = (log2fc < -1) & (neg_log_p > 2) 16 ns = ~sig_up & ~sig_down 17 18 fig, ax = plt.subplots(figsize=(7, 5.5)) 19 20 # Gradient density background (hexbin) 21 hb = ax.hexbin(log2fc, neg_log_p, gridsize=30, cmap='Blues', alpha=0.25, 22 mincnt=1, linewidths=0.0, zorder=0) 23 24 # Fold-change threshold shading 25 ax.axvspan(-1, 1, alpha=0.06, color=COLORS['ref_line'], zorder=0, label='|FC| < 2') 26 ax.axvspan(1, log2fc.max() + 1, alpha=0.04, color=PALETTE[3], zorder=0) 27 ax.axvspan(log2fc.min() - 1, -1, alpha=0.04, color=PALETTE[0], zorder=0) 28 29 # Subtle grid 30 ax.grid(alpha=0.15, linestyle='-', color=COLORS['grid']) 31 ax.set_axisbelow(True) 32 33 # Scatter points 34 ax.scatter(log2fc[ns], neg_log_p[ns], c=COLORS['neutral'], alpha=0.35, s=8, 35 label=f'NS ({ns.sum()})', zorder=2) 36 ax.scatter(log2fc[sig_up], neg_log_p[sig_up], c=PALETTE[3], alpha=0.7, s=15, 37 label=f'Up ({sig_up.sum()})', edgecolors='white', linewidths=0.3, zorder=3) 38 ax.scatter(log2fc[sig_down], neg_log_p[sig_down], c=PALETTE[0], alpha=0.7, s=15, 39 label=f'Down ({sig_down.sum()})', edgecolors='white', linewidths=0.3, zorder=3) 40 41 # Threshold lines 42 ax.axhline(2, color=COLORS['ref_line'], linestyle='--', linewidth=0.8, alpha=0.7) 43 ax.axvline(1, color=COLORS['ref_line'], linestyle='--', linewidth=0.8, alpha=0.7) 44 ax.axvline(-1, color=COLORS['ref_line'], linestyle='--', linewidth=0.8, alpha=0.7) 45 46 # Gene labels for top hits (top 5 by significance) 47 all_sig = np.where(sig_up | sig_down)[0] 48 if len(all_sig) > 0: 49 top_idx = all_sig[np.argsort(neg_log_p[all_sig])[-5:]] 50 for idx in top_idx: 51 ax.annotate(gene_names[idx], 52 xy=(log2fc[idx], neg_log_p[idx]), 53 xytext=(log2fc[idx] + 0.3 * np.sign(log2fc[idx]), 54 neg_log_p[idx] + 0.5), 55 fontsize=7, fontstyle='italic', 56 color=COLORS['text'], 57 arrowprops=dict(arrowstyle='->', color=COLORS['text'], lw=0.7), 58 bbox=dict(boxstyle='round,pad=0.15', facecolor='white', 59 edgecolor=COLORS['neutral'], alpha=0.85)) 60 61 ax.set_xlabel('$\\log_2$(Fold Change)', fontsize=11) 62 ax.set_ylabel('$-\\log_{10}$(p-value)', fontsize=11) 63 ax.legend(frameon=False, labelspacing=0.35, handlelength=1.6, fontsize=8, loc='best', 64 fancybox=True) 65 ax.spines['top'].set_visible(False) 66 ax.spines['right'].set_visible(False) 67 fig.tight_layout() 68 save_fig(fig, 'figures/fig_volcano.pdf')