{"spec_id":"scatter-regression-polynomial","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nscatter-regression-polynomial: Scatter Plot with Polynomial Regression\nLibrary: matplotlib 3.11.1 | Python 3.13.14\nQuality: 92/100 | Updated: 2026-08-11\n\"\"\"\n\nimport os\n\nimport matplotlib.patheffects as patheffects\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Theme tokens (see prompts/default-style-guide.md \"Background\" + \"Theme-adaptive Chrome\")\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\"  # Imprint palette position 1 — ALWAYS first series\nSECONDARY = \"#C475FD\"  # Imprint palette position 2\n\n# Data - Modeling diminishing returns (economics example)\nnp.random.seed(42)\nx = np.linspace(0, 10, 80)\n# Quadratic relationship: y = -0.5x² + 6x + 5 + noise\ny = -0.5 * x**2 + 6 * x + 5 + np.random.normal(0, 2, len(x))\n\n# Fit polynomial regression (degree 2 - quadratic)\ncoeffs = np.polyfit(x, y, 2)\npoly = np.poly1d(coeffs)\nx_smooth = np.linspace(x.min(), x.max(), 200)\ny_fit = poly(x_smooth)\n\n# Calculate R² value\ny_pred = poly(x)\nss_res = np.sum((y - y_pred) ** 2)\nss_tot = np.sum((y - np.mean(y)) ** 2)\nr_squared = 1 - (ss_res / ss_tot)\n\n# Plot — canonical landscape canvas: figsize(8, 4.5) @ dpi=400 => 3200x1800px\nfig, ax = plt.subplots(figsize=(8, 4.5), dpi=400, facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\n# Scatter points with transparency\nax.scatter(x, y, s=140, alpha=0.8, color=BRAND, edgecolors=PAGE_BG, linewidth=0.5, label=\"Data points\", zorder=3)\n\n# Confidence band (approximate using residual standard error)\nresiduals = y - y_pred\nstd_err = np.std(residuals)\nax.fill_between(\n    x_smooth,\n    y_fit - 1.96 * std_err,\n    y_fit + 1.96 * std_err,\n    alpha=0.15,\n    color=SECONDARY,\n    label=\"95% confidence band\",\n    zorder=1,\n)\n\n# Polynomial regression curve — a soft page-colored halo (patheffects) lifts the\n# curve off the scatter cloud without darkening its color in either theme.\n(fit_line,) = ax.plot(x_smooth, y_fit, color=SECONDARY, linewidth=2.5, label=\"Polynomial fit (degree 2)\", zorder=2)\nfit_line.set_path_effects([patheffects.Stroke(linewidth=5, foreground=PAGE_BG, alpha=0.6), patheffects.Normal()])\n\n# Highlight the curve's peak (vertex of the parabola) — the \"diminishing returns\"\n# insight the plot is telling: returns rise, crest here, then decline.\na, b, c = coeffs\nvertex_x = -b / (2 * a)\nif x.min() <= vertex_x <= x.max():\n    vertex_y = poly(vertex_x)\n    ax.plot(\n        vertex_x,\n        vertex_y,\n        marker=\"o\",\n        markersize=11,\n        markerfacecolor=PAGE_BG,\n        markeredgecolor=SECONDARY,\n        markeredgewidth=2,\n        zorder=4,\n    )\n    ax.annotate(\n        \"Peak return\",\n        xy=(vertex_x, vertex_y),\n        xytext=(vertex_x, vertex_y + 0.14 * (y.max() - y.min())),\n        ha=\"center\",\n        fontsize=8,\n        color=INK_SOFT,\n        arrowprops={\"arrowstyle\": \"-\", \"color\": INK_SOFT, \"linewidth\": 0.8},\n    )\n\n# Format polynomial equation with mathtext for a cleaner, typeset look\nequation = f\"$y = {a:.2f}x^2 + {b:.2f}x + {c:.2f}$\"\n\n# Add R² and equation annotation (top-left, well clear of the legend which lives outside the axes)\nannotation_text = f\"{equation}\\n$R^2 = {r_squared:.3f}$\"\nax.annotate(\n    annotation_text,\n    xy=(0.03, 0.97),\n    xycoords=\"axes fraction\",\n    fontsize=9,\n    verticalalignment=\"top\",\n    bbox={\"boxstyle\": \"round,pad=0.5\", \"facecolor\": ELEVATED_BG, \"edgecolor\": INK_SOFT, \"alpha\": 0.9},\n    color=INK,\n)\n\n# Style\nax.set_xlabel(\"Investment (units)\", fontsize=10, color=INK)\nax.set_ylabel(\"Return (units)\", fontsize=10, color=INK)\nax.set_title(\n    \"scatter-regression-polynomial · python · matplotlib · anyplot.ai\", fontsize=12, fontweight=\"medium\", color=INK\n)\nax.tick_params(axis=\"both\", labelsize=8, colors=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)\n\nax.yaxis.grid(True, alpha=0.15, linewidth=0.8, color=INK)\n\n# Legend positioned outside the axes (right margin reserved via subplots_adjust below)\n# so it never collides with the annotation box in the top-left corner.\nleg = ax.legend(fontsize=8, loc=\"center left\", bbox_to_anchor=(1.02, 0.5), frameon=True)\nif leg:\n    leg.get_frame().set_facecolor(ELEVATED_BG)\n    leg.get_frame().set_edgecolor(INK_SOFT)\n    plt.setp(leg.get_texts(), color=INK_SOFT)\n\nfig.subplots_adjust(left=0.08, right=0.68, top=0.9, bottom=0.13)\nplt.savefig(f\"plot-{THEME}.png\", dpi=400, facecolor=PAGE_BG)  # bbox_inches MUST stay default (None)\n"}