{"spec_id":"elbow-curve","library":"muix","language":"javascript","code":"// anyplot.ai\n// elbow-curve: Elbow Curve for K-Means Clustering\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 92/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { useXScale, useYScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst X_PAD = 0.04; // share of the k range added on both sides so the outermost markers sit inside the plot\nconst Y_PAD = 0.08; // share of the largest inertia left free above it\nconst ELBOW_R = 11; // px radius of the highlighted elbow marker\nconst TITLE = \"elbow-curve · javascript · muix · anyplot.ai\";\nconst HEADER_H = 84;\n\n// Columns: set these to your data's column names\nconst K = \"Number of clusters (k)\"; // role: k_values\nconst INERTIA = \"Inertia (within-cluster sum of squares)\"; // role: inertia\n\n// Data: replace this block with your own records, one object per row\n// K-means inertia for a customer segmentation model, k = 1 to 10\nconst data = [\n  { [K]: 1, [INERTIA]: 1250 },\n  { [K]: 2, [INERTIA]: 690 },\n  { [K]: 3, [INERTIA]: 410 },\n  { [K]: 4, [INERTIA]: 260 },\n  { [K]: 5, [INERTIA]: 195 },\n  { [K]: 6, [INERTIA]: 165 },\n  { [K]: 7, [INERTIA]: 145 },\n  { [K]: 8, [INERTIA]: 130 },\n  { [K]: 9, [INERTIA]: 118 },\n  { [K]: 10, [INERTIA]: 108 },\n];\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => Number.isFinite(d[INERTIA])).sort((a, b) => a[K] - b[K]);\nconst ks = rows.map((d) => d[K]);\nconst inertia = rows.map((d) => d[INERTIA]);\nconst kLo = ks[0];\nconst kHi = ks[ks.length - 1];\nconst yLo = Math.min(...inertia);\nconst yHi = Math.max(...inertia);\n\n// Elbow: the point farthest from the straight line joining the first and last points,\n// both axes scaled to 0-1 so k and inertia weigh equally\nconst chordDistance = rows.map((d) => 1 - (d[K] - kLo) / (kHi - kLo) - (d[INERTIA] - yLo) / (yHi - yLo));\nconst elbowIdx = chordDistance.indexOf(Math.max(...chordDistance));\nconst elbowK = ks[elbowIdx];\nconst elbowSeries = inertia.map((v, i) => (i === elbowIdx ? v : null));\nconst dropToElbow = (1 - inertia[elbowIdx] / inertia[0]) * 100;\nconst dropAfter = (1 - inertia[inertia.length - 1] / inertia[elbowIdx]) * 100;\nconst subtitle = `k = ${kLo} to ${kHi} · elbow at k = ${elbowK}, the point farthest from the line joining the first and last k · inertia falls ${dropToElbow.toFixed(0)}% up to the elbow and ${dropAfter.toFixed(0)}% after it`;\n\n// Dashed guide from the top of the plot down to the elbow marker, with the label beside it\nfunction ElbowGuide() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const { top } = useDrawingArea();\n  const x = xScale(elbowK);\n  const y = yScale(inertia[elbowIdx]);\n  return (\n    <g>\n      <line x1={x} x2={x} y1={top} y2={y - ELBOW_R - 6} stroke={t.inkSoft} strokeWidth={2} strokeDasharray=\"6 6\" />\n      <text x={x + 12} y={top + 18} fontSize={16} fontWeight={600} fill={t.ink}>\n        {`Elbow at k = ${elbowK}`}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: HEADER_H, padding: \"22px 40px 0\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, marginTop: 6 }}>{subtitle}</div>\n      </div>\n      <LineChart\n        width={width}\n        height={height - HEADER_H}\n        skipAnimation\n        hideLegend\n        grid={{ horizontal: true }}\n        margin={{ top: 24, right: 48, bottom: 16, left: 24 }}\n        xAxis={[\n          {\n            data: ks,\n            scaleType: \"linear\",\n            min: kLo - (kHi - kLo) * X_PAD,\n            max: kHi + (kHi - kLo) * X_PAD,\n            tickMinStep: 1,\n            valueFormatter: (v) => v.toFixed(0),\n            label: K,\n            height: 68,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            max: yHi * (1 + Y_PAD),\n            label: INERTIA,\n            width: 92,\n            valueFormatter: (v) => v.toLocaleString(\"en-US\"),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={[\n          {\n            id: \"inertia\",\n            data: inertia,\n            label: INERTIA,\n            color: t.palette[0],\n            showMark: true,\n            shape: \"circle\",\n            curve: \"monotoneX\",\n            area: true,\n          },\n          {\n            id: \"elbow\",\n            data: elbowSeries,\n            label: `Elbow (k = ${elbowK})`,\n            color: t.palette[0],\n            showMark: true,\n            shape: \"circle\",\n            disableHighlight: true,\n          },\n        ]}\n        sx={{\n          '& .MuiLineChart-area[data-series=\"inertia\"]': { fillOpacity: 0.1 },\n          '& .MuiLineChart-line[data-series=\"inertia\"]': { strokeWidth: 3 },\n          '& .MuiLineChart-mark[data-series=\"inertia\"]': { r: 6, fill: t.pageBg, strokeWidth: 2.5 },\n          '& .MuiLineChart-mark[data-series=\"elbow\"]': { r: ELBOW_R, fill: t.palette[0], stroke: t.ink, strokeWidth: 2.5 },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      >\n        <ElbowGuide />\n      </LineChart>\n    </div>\n  );\n}\n"}