{"spec_id":"elbow-curve","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nelbow-curve: Elbow Curve for K-Means Clustering\nLibrary: matplotlib 3.10.9 | Python 3.13.13\nQuality: 94/100 | Updated: 2026-05-10\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\"\nBRAND = \"#009E73\"  # Okabe-Ito position 1 — ALWAYS first series\n\n# Generate realistic inertia decay pattern for K-means elbow curve\nnp.random.seed(42)\nk_values = np.arange(1, 11)\n\nbase_inertia = 5000\ninertias = []\nfor k in k_values:\n    # Exponential decay with elbow effect at k=4\n    if k <= 4:\n        inertia = base_inertia * np.exp(-0.35 * (k - 1))\n    else:\n        inertia = base_inertia * np.exp(-0.35 * 3) * np.exp(-0.15 * (k - 4))\n    inertia += np.random.uniform(-50, 50)\n    inertias.append(max(inertia, 100))\n\ninertias = np.array(inertias)\n\n# Identify the elbow point\nelbow_k = 4\nelbow_inertia = inertias[elbow_k - 1]\n\n# Plot\nfig, ax = plt.subplots(figsize=(16, 9), facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\nax.plot(\n    k_values,\n    inertias,\n    color=BRAND,\n    linewidth=3,\n    marker=\"o\",\n    markersize=12,\n    markerfacecolor=BRAND,\n    markeredgecolor=PAGE_BG,\n    markeredgewidth=0.5,\n)\n\n# Highlight the elbow point\nax.scatter([elbow_k], [elbow_inertia], s=400, color=BRAND, edgecolors=PAGE_BG, linewidths=0.5, zorder=5)\n\nax.annotate(\n    f\"Elbow Point\\n(k={elbow_k})\",\n    xy=(elbow_k, elbow_inertia),\n    xytext=(elbow_k + 1.8, elbow_inertia + 600),\n    fontsize=18,\n    fontweight=\"bold\",\n    color=INK,\n    arrowprops={\"arrowstyle\": \"->\", \"color\": INK_SOFT, \"lw\": 2.5},\n    bbox={\"boxstyle\": \"round,pad=0.5\", \"facecolor\": ELEVATED_BG, \"edgecolor\": INK_SOFT, \"alpha\": 0.9},\n)\n\n# Add diminishing returns region\nax.axvspan(elbow_k, max(k_values), alpha=0.1, color=INK_SOFT)\n\n# Style\nax.set_xlabel(\"Number of Clusters (k)\", fontsize=20, color=INK)\nax.set_ylabel(\"Inertia (Within-Cluster Sum of Squares)\", fontsize=20, color=INK)\nax.set_title(\"elbow-curve · matplotlib · anyplot.ai\", fontsize=24, fontweight=\"medium\", color=INK)\nax.set_xticks(k_values)\nax.tick_params(axis=\"both\", labelsize=16, colors=INK_SOFT, labelcolor=INK_SOFT)\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nfor s in (\"left\", \"bottom\"):\n    ax.spines[s].set_color(INK_SOFT)\nax.yaxis.grid(True, alpha=0.10, linewidth=0.8, color=INK_SOFT)\n\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=300, bbox_inches=\"tight\", facecolor=PAGE_BG)\n"}