{"spec_id":"curve-bias-variance-tradeoff","library":"muix","language":"javascript","code":"// anyplot.ai\n// curve-bias-variance-tradeoff: Bias-Variance Tradeoff Curve\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 90/100 | Updated: 2026-11-08\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst ERROR_AXIS = \"Prediction error\"; // the y quantity of every bias-variance decomposition\nconst HEADROOM_SHARE = 0.08; // space above the highest total error, as a share of it\nconst LABEL_GAP = 20; // minimum vertical distance between two end-of-curve labels, in px\n\n// Columns: set these to your data's column names\nconst COMPLEXITY = \"Model complexity (low → high)\"; // role: model_complexity\nconst BIAS_SQUARED = \"Bias²\"; // role: bias_squared\nconst VARIANCE = \"Variance\"; // role: variance\nconst IRREDUCIBLE = \"Irreducible error\"; // role: irreducible_error\nconst TOTAL = \"Total error\"; // role: total_error\n\n// Data: replace this block with your own records, one object per complexity value\n// Theoretical decomposition over 80 complexity values: bias² falls as 2.4 / (1 + 0.3c), variance rises\n// as 0.005c², the noise floor stays at 0.15, and the total error is their sum\nconst data = Array.from({ length: 80 }, (_, i) => {\n  const c = 1 + (i * 19) / 79;\n  const biasSquared = 2.4 / (1 + 0.3 * c);\n  const variance = 0.005 * c * c;\n  const irreducible = 0.15;\n  return {\n    [COMPLEXITY]: c,\n    [BIAS_SQUARED]: biasSquared,\n    [VARIANCE]: variance,\n    [IRREDUCIBLE]: irreducible,\n    [TOTAL]: biasSquared + variance + irreducible,\n  };\n});\n\n// Plot: reads only data and the constants above\nconst rows = [...data].sort((a, b) => a[COMPLEXITY] - b[COMPLEXITY]);\nconst complexity = rows.map((d) => d[COMPLEXITY]);\nconst optimum = rows.reduce((best, d) => (d[TOTAL] < best[TOTAL] ? d : best), rows[0]);\nconst yMax = Math.max(...rows.map((d) => d[TOTAL])) * (1 + HEADROOM_SHARE);\n\n// Total error carries the story, so it leads in palette order and line weight; the irreducible noise\n// floor is a baseline and takes the neutral ink anchor\nconst curves = [\n  { id: \"total\", column: TOTAL, color: t.palette[0], width: 4, dash: \"none\" },\n  { id: \"bias\", column: BIAS_SQUARED, color: t.palette[1], width: 3, dash: \"10 6\" },\n  { id: \"variance\", column: VARIANCE, color: t.palette[2], width: 3.5, dash: \"2 6\" },\n  { id: \"irreducible\", column: IRREDUCIBLE, color: t.ink, width: 1.5, dash: \"4 4\" },\n];\nconst series = curves.map((c) => ({\n  type: \"line\" as const,\n  id: c.id,\n  label: c.column,\n  data: rows.map((d) => d[c.column]),\n  color: c.color,\n  curve: \"monotoneX\" as const,\n  showMark: false,\n}));\n\nconst TITLE = \"curve-bias-variance-tradeoff · javascript · muix · anyplot.ai\";\nconst formula = `${TOTAL} = ${BIAS_SQUARED} + ${VARIANCE} + ${IRREDUCIBLE}`;\nconst HEADER_H = 88;\n\nfunction Zones() {\n  const xScale = useXScale();\n  const { left, top, width, height } = useDrawingArea();\n  const xOpt = xScale(optimum[COMPLEXITY])!;\n  return (\n    <g>\n      <rect x={left} y={top} width={xOpt - left} height={height} fill={t.inkSoft} fillOpacity={0.07} />\n      <rect x={xOpt} y={top} width={left + width - xOpt} height={height} fill={t.inkSoft} fillOpacity={0.13} />\n      <text x={(left + xOpt) / 2} y={top + 28} fill={t.inkSoft} fontSize={15} fontWeight={600} letterSpacing={1} textAnchor=\"middle\">\n        UNDERFITTING\n      </text>\n      <text x={(xOpt + left + width) / 2} y={top + 28} fill={t.inkSoft} fontSize={15} fontWeight={600} letterSpacing={1} textAnchor=\"middle\">\n        OVERFITTING\n      </text>\n    </g>\n  );\n}\n\nfunction CurveLabels() {\n  const yScale = useYScale();\n  const { left, width } = useDrawingArea();\n  const last = rows[rows.length - 1];\n  // Labels sit at each curve's right end; only the labels move apart when two ends are close\n  const labels = curves.map((c) => ({ ...c, y: yScale(last[c.column])! })).sort((a, b) => a.y - b.y);\n  labels.forEach((l, i) => {\n    if (i > 0 && l.y - labels[i - 1].y < LABEL_GAP) l.y = labels[i - 1].y + LABEL_GAP;\n  });\n  return (\n    <g>\n      {labels.map((l) => (\n        <text key={l.id} x={left + width + 12} y={l.y} dominantBaseline=\"middle\" fill={l.color} fontSize={16} fontWeight={500}>\n          {l.column}\n        </text>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <Box sx={{ height: HEADER_H, display: \"flex\", flexDirection: \"column\", justifyContent: \"center\", alignItems: \"center\", gap: \"6px\", pt: \"8px\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 16, color: t.inkSoft, lineHeight: 1.2 }}>{formula}</Typography>\n      </Box>\n      <ChartsContainer\n        width={width}\n        height={height - HEADER_H}\n        series={series}\n        skipAnimation\n        margin={{ top: 16, right: 180, bottom: 16, left: 32 }}\n        xAxis={[\n          {\n            scaleType: \"linear\",\n            data: complexity,\n            min: complexity[0],\n            max: complexity[complexity.length - 1],\n            label: COMPLEXITY,\n            height: 64,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            max: yMax,\n            label: ERROR_AXIS,\n            width: 76,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          ...Object.fromEntries(\n            curves.map((c) => [\n              `& .MuiLineChart-line[data-series=\"${c.id}\"]`,\n              { strokeWidth: c.width, strokeDasharray: c.dash, strokeLinecap: \"round\" },\n            ]),\n          ),\n        }}\n      >\n        <Zones />\n        <LinePlot />\n        <ChartsReferenceLine\n          x={optimum[COMPLEXITY]}\n          label={`Optimum at ${optimum[COMPLEXITY].toFixed(1)} (minimum ${TOTAL.toLowerCase()} ${optimum[TOTAL].toFixed(2)})`}\n          labelAlign=\"end\"\n          lineStyle={{ stroke: t.ink, strokeDasharray: \"6 4\", strokeWidth: 1.5 }}\n          labelStyle={{ fill: t.ink, fontSize: 14, fontWeight: 600 }}\n        />\n        <CurveLabels />\n        <ChartsXAxis />\n        <ChartsYAxis />\n      </ChartsContainer>\n    </Box>\n  );\n}\n"}