{"spec_id":"gain-curve","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\ngain-curve: Cumulative Gains Chart\nLibrary: matplotlib 3.10.9 | Python 3.13.13\nQuality: 95/100 | Updated: 2026-05-11\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Theme tokens\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\nBRAND = \"#009E73\"  # Okabe-Ito position 1\nSECONDARY = \"#C475FD\"  # Okabe-Ito position 2\nNEUTRAL = INK_MUTED\n\n# Data: Generate synthetic classification data (customer response model)\nnp.random.seed(42)\nn_samples = 1000\n\n# Create customer features that influence response\ncustomer_value = np.random.randn(n_samples)\ncustomer_engagement = np.random.randn(n_samples)\n\n# True underlying probability (strong signal)\nlatent_score = 1.5 * customer_value + 1.0 * customer_engagement\ntrue_prob = 1 / (1 + np.exp(-latent_score))\ny_true = (np.random.rand(n_samples) < true_prob).astype(int)\n\n# Model predicted probabilities (captures signal well with some noise)\ny_score = 1 / (1 + np.exp(-(latent_score + np.random.randn(n_samples) * 0.5)))\n\n# Calculate cumulative gains curve\nsorted_indices = np.argsort(y_score)[::-1]\ny_true_sorted = y_true[sorted_indices]\n\n# Cumulative gains: percentage of population vs percentage of positives captured\ntotal_positives = np.sum(y_true)\ncumulative_positives = np.cumsum(y_true_sorted)\ngains = cumulative_positives / total_positives * 100\n\n# Percentage of population targeted\npopulation_percentage = np.arange(1, n_samples + 1) / n_samples * 100\n\n# Add origin point (0, 0) for proper plotting\npopulation_percentage = np.insert(population_percentage, 0, 0)\ngains = np.insert(gains, 0, 0)\n\n# Create perfect model curve (captures all positives immediately)\npositive_rate = total_positives / n_samples * 100\nperfect_x = np.array([0, positive_rate, 100])\nperfect_y = np.array([0, 100, 100])\n\n# Plot\nfig, ax = plt.subplots(figsize=(16, 9), facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\n# Plot model gains curve (brand green - first series)\nax.plot(population_percentage, gains, color=BRAND, linewidth=3, label=\"Model\", zorder=3)\n\n# Plot random baseline (diagonal)\nax.plot([0, 100], [0, 100], color=INK_SOFT, linewidth=2, linestyle=\"--\", label=\"Random (Baseline)\", zorder=2)\n\n# Plot perfect model\nax.plot(perfect_x, perfect_y, color=INK_MUTED, linewidth=2, linestyle=\":\", label=\"Perfect Model\", zorder=2)\n\n# Fill area between model and random baseline\nax.fill_between(population_percentage, gains, population_percentage, alpha=0.15, color=BRAND, zorder=1)\n\n# Styling\nax.set_xlabel(\"Population Targeted (%)\", fontsize=20, color=INK)\nax.set_ylabel(\"Positive Cases Captured (%)\", fontsize=20, color=INK)\nax.set_title(\"gain-curve · matplotlib · anyplot.ai\", fontsize=24, fontweight=\"medium\", color=INK)\n\nax.set_xlim(0, 100)\nax.set_ylim(0, 100)\nax.set_aspect(\"equal\")\n\nax.tick_params(axis=\"both\", labelsize=16, colors=INK_SOFT)\nfor s in (\"left\", \"bottom\"):\n    ax.spines[s].set_color(INK_SOFT)\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\n\nax.grid(True, alpha=0.10, linewidth=0.8, color=INK)\n\nleg = ax.legend(fontsize=16, loc=\"lower right\")\nif leg:\n    leg.get_frame().set_facecolor(ELEVATED_BG)\n    leg.get_frame().set_edgecolor(INK_SOFT)\n    leg.get_frame().set_linewidth(0.8)\n    plt.setp(leg.get_texts(), color=INK_SOFT)\n\n# Add annotation showing key insight\nidx_20 = np.searchsorted(population_percentage, 20)\ngain_at_20 = gains[idx_20]\nax.annotate(\n    f\"Top 20% captures {gain_at_20:.0f}%\\nof positive cases\",\n    xy=(20, gain_at_20),\n    xytext=(35, gain_at_20 - 15),\n    fontsize=14,\n    color=INK,\n    arrowprops={\"arrowstyle\": \"->\", \"color\": BRAND, \"lw\": 2},\n    bbox={\"boxstyle\": \"round,pad=0.3\", \"facecolor\": ELEVATED_BG, \"edgecolor\": INK_SOFT, \"alpha\": 0.9},\n)\n\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=300, bbox_inches=\"tight\", facecolor=PAGE_BG)\n"}