{"spec_id":"curve-bias-variance-tradeoff","library":"plotnine","language":"python","code":"\"\"\" anyplot.ai\ncurve-bias-variance-tradeoff: Bias-Variance Tradeoff Curve\nLibrary: plotnine 0.15.9 | Python 3.14.10\nQuality: 83/100 | Updated: 2026-11-26\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom plotnine import (\n    aes,\n    annotate,\n    element_blank,\n    element_line,\n    element_rect,\n    element_text,\n    geom_line,\n    geom_vline,\n    ggplot,\n    labs,\n    scale_color_manual,\n    scale_linetype_manual,\n    scale_size_manual,\n    scale_x_continuous,\n    scale_y_continuous,\n    theme,\n)\n\n\n# Theme tokens\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\n# Imprint palette: all eight positions, one per curve in order\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\n\n# Columns: set these to your table's column names\nCOMPLEXITY = \"Model Complexity\"  # role: model_complexity\nBIAS = \"Bias²\"  # role: bias_squared\nVARIANCE = \"Variance\"  # role: variance\nIRREDUCIBLE = \"Irreducible Error\"  # role: irreducible_error\nTOTAL = \"Total Error\"  # role: total_error\nERROR = \"Prediction Error\"  # role: extra\nCURVE = \"Curve\"  # role: extra\n\n# Data: replace this block with your own table, for example df = pd.read_csv(\"curves.csv\")\ncomplexity = np.linspace(0.1, 10, 100)\nbias_sq = 1.0 / (1.0 + complexity * 0.4) ** 0.9\nvariance = 0.018 * complexity**1.6\nirreducible = np.full(len(complexity), 0.20)\ndf = pd.DataFrame(\n    {\n        COMPLEXITY: complexity,\n        BIAS: bias_sq,\n        VARIANCE: variance,\n        IRREDUCIBLE: irreducible,\n        TOTAL: bias_sq + variance + irreducible,\n    }\n)\n\n# Plot: reads only df and the constants above\ncurves = [BIAS, VARIANCE, IRREDUCIBLE, TOTAL]\nlong_df = df.melt(id_vars=COMPLEXITY, value_vars=curves, var_name=CURVE, value_name=ERROR)\nlong_df[CURVE] = pd.Categorical(long_df[CURVE], categories=curves)\n\ncolors = dict(zip(curves, IMPRINT_PALETTE, strict=False))\nlinetypes = dict(zip(curves, [\"dashed\", \"dashdot\", \"dotted\", \"solid\"], strict=True))\nline_sizes = dict(zip(curves, [0.9, 0.9, 0.7, 1.3], strict=True))\n\nx_min, x_max = df[COMPLEXITY].min(), df[COMPLEXITY].max()\nx_span = x_max - x_min\ny_top = df[TOTAL].max() * 1.05\nopt_idx = df[TOTAL].idxmin()\nopt_x = df.loc[opt_idx, COMPLEXITY]\nopt_y = df.loc[opt_idx, TOTAL]\n\n\n# Direct curve labels, each placed on its own curve at a well-separated position\nlabel_x = x_min + x_span * np.array([0.21, 0.84, 0.64, 0.57])\nlabel_y = [\n    np.interp(label_x[0], df[COMPLEXITY], df[BIAS]) + 0.06,\n    np.interp(label_x[1], df[COMPLEXITY], df[VARIANCE]) + 0.05,\n    df[IRREDUCIBLE].iloc[0] - 0.06,\n    np.interp(label_x[3], df[COMPLEXITY], df[TOTAL]) + 0.06,\n]\n\nanyplot_theme = theme(\n    figure_size=(8, 4.5),\n    plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n    panel_background=element_rect(fill=PAGE_BG),\n    panel_grid_major_y=element_line(color=INK_MUTED, size=0.3),\n    panel_grid_major_x=element_blank(),\n    panel_grid_minor=element_blank(),\n    panel_border=element_blank(),\n    axis_line=element_line(color=INK_SOFT, size=0.5),\n    axis_ticks=element_line(color=INK_SOFT, size=0.3),\n    axis_title=element_text(color=INK, size=10),\n    axis_text=element_text(color=INK_SOFT, size=8),\n    plot_title=element_text(color=INK, size=12),\n    legend_position=\"none\",\n)\n\nplot = (\n    ggplot(long_df, aes(x=COMPLEXITY, y=ERROR, color=CURVE, linetype=CURVE, size=CURVE))\n    # Underfitting (left) and overfitting (right) zones around the optimum\n    + annotate(\n        \"rect\",\n        xmin=[x_min, opt_x],\n        xmax=[opt_x, x_max],\n        ymin=[0.0, 0.0],\n        ymax=[y_top, y_top],\n        fill=INK_MUTED,\n        alpha=[0.04, 0.12],\n    )\n    + annotate(\n        \"text\", x=x_min + 0.02 * x_span, y=y_top * 0.97, label=\"Underfitting\", color=INK_MUTED, size=9, ha=\"left\"\n    )\n    + annotate(\n        \"text\", x=x_max - 0.02 * x_span, y=y_top * 0.97, label=\"Overfitting\", color=INK_MUTED, size=9, ha=\"right\"\n    )\n    + geom_line()\n    + geom_vline(xintercept=opt_x, color=INK_MUTED, linetype=\"dashed\", size=0.5)\n    + annotate(\n        \"text\",\n        x=label_x,\n        y=label_y,\n        label=curves,\n        color=[colors[c] for c in curves],\n        size=9,\n        ha=[\"left\", \"right\", \"left\", \"left\"],\n    )\n    + annotate(\n        \"text\",\n        x=opt_x + 0.025 * x_span,\n        y=opt_y - 0.07,\n        label=\"Optimal\\nComplexity\",\n        color=INK_MUTED,\n        size=8.5,\n        ha=\"left\",\n    )\n    + annotate(\n        \"text\",\n        x=opt_x + 0.04 * x_span,\n        y=y_top * 0.93 / 1.05,\n        label=f\"{TOTAL} = {BIAS} + {VARIANCE} + {IRREDUCIBLE}\",\n        color=INK_SOFT,\n        size=8.5,\n        ha=\"left\",\n    )\n    + scale_color_manual(values=colors)\n    + scale_linetype_manual(values=linetypes)\n    + scale_size_manual(values=line_sizes)\n    + scale_x_continuous(\n        name=COMPLEXITY, breaks=[x_min, x_max], labels=[\"Low\", \"High\"], limits=(x_min, x_max), expand=(0, 0)\n    )\n    + scale_y_continuous(name=ERROR, limits=(0.0, y_top))\n    + labs(title=\"curve-bias-variance-tradeoff · python · plotnine · anyplot.ai\")\n    + anyplot_theme\n)\n\n# Save\nplot.save(f\"plot-{THEME}.png\", dpi=400, width=8, height=4.5, units=\"in\")\n"}