{"spec_id":"lift-curve","library":"muix","language":"javascript","code":"// anyplot.ai\n// lift-curve: Model Lift Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst SLICES = 20; // the curve is evaluated at every 1/20 of the ranked population (5 % steps)\nconst PERCENT_MAX = 100; // the targeted share runs from 0 to 100 %\nconst X_TICK_STEPS = 10; // one tick every tenth of the population\nconst NO_LIFT = 1; // a lift of 1 is random selection\nconst KEY_PERCENTS = [10, 25, 50]; // targeted shares whose lift is written beside the curve\nconst Y_HEADROOM_SHARE = 0.12; // room above the highest lift\nconst X_PAD_SHARE = 0.015; // room right of 100 % so the last mark stays inside the plot\n\n// Columns: set these to your data's column names\nconst FRAUD = \"Fraudulent transaction (1 = yes)\"; // role: y_true\nconst SCORE = \"Model fraud score\"; // role: y_score\n\n// Data: replace this block with your own records, one object per case\n// 2,000 card transactions with a 3 % fraud rate; fraud cases score around 0.75 and\n// legitimate ones around 0.30, with enough noise that the model is far from perfect.\nconst data = (() => {\n  let seed = 42;\n  const rand = () => {\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    return seed / 0x7fffffff;\n  };\n  return Array.from({ length: 2000 }, () => {\n    const fraud = rand() < 0.03 ? 1 : 0;\n    const score = Math.min(1, Math.max(0, (fraud ? 0.75 : 0.3) + (rand() - 0.5) * 0.7));\n    return { [FRAUD]: fraud, [SCORE]: Number(score.toFixed(4)) };\n  });\n})();\n\n// Plot: reads only data and the constants above\n// Cases ranked by score, highest first: the order in which the model would target them\nconst ranked = data\n  .filter((d) => d[FRAUD] != null && d[SCORE] != null)\n  .sort((a, b) => b[SCORE] - a[SCORE]);\nconst n = ranked.length;\nconst cumulativePositives: number[] = [];\nlet running = 0;\nfor (const d of ranked) {\n  running += d[FRAUD] === 1 ? 1 : 0;\n  cumulativePositives.push(running);\n}\nconst positives = running;\nconst baseRate = positives / n;\n\n// Cumulative lift: the response rate among the top share of the ranking over the base rate\nconst percents = Array.from({ length: SLICES }, (_, i) => ((i + 1) * PERCENT_MAX) / SLICES);\nconst lift = percents.map((p) => {\n  const cutoff = Math.max(1, Math.round((p / PERCENT_MAX) * n));\n  return cumulativePositives[cutoff - 1] / cutoff / baseRate;\n});\nconst liftMax = Math.max(...lift, NO_LIFT);\nconst keyPoints = KEY_PERCENTS.map((p) => percents.indexOf(p)).filter((i) => i >= 0);\n\nconst TITLE = \"lift-curve · javascript · muix · anyplot.ai\";\nconst SUBTITLE =\n  `n = ${n.toLocaleString(\"en-US\")} cases · ${positives} positive (base rate ${(baseRate * 100).toFixed(1)} %) · ` +\n  `marks every ${PERCENT_MAX / SLICES} % of the ranked population`;\nconst HEADER_H = 84;\n\nfunction KeyLiftLabels() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g>\n      {keyPoints.map((i) => (\n        <text\n          key={percents[i]}\n          x={xScale(percents[i]) + 12}\n          y={yScale(lift[i]) - 14}\n          textAnchor=\"start\"\n          fontSize={15}\n          fontWeight={600}\n          fill={t.ink}\n        >\n          {`${lift[i].toFixed(2)}× at ${percents[i]} %`}\n        </text>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\", overflow: \"hidden\" }}>\n      <Box sx={{ height: HEADER_H, pt: \"14px\", textAlign: \"center\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.3 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.6 }}>{SUBTITLE}</Typography>\n      </Box>\n      <LineChart\n        width={width}\n        height={height - HEADER_H}\n        skipAnimation\n        hideLegend\n        grid={{ horizontal: true }}\n        margin={{ top: 16, right: 48, bottom: 16, left: 20 }}\n        series={[\n          {\n            id: \"lift\",\n            data: lift,\n            label: \"Cumulative lift\",\n            color: t.palette[0],\n            curve: \"linear\",\n            showMark: true,\n            shape: \"circle\",\n            valueFormatter: (v) => `${v.toFixed(2)}×`,\n          },\n        ]}\n        xAxis={[\n          {\n            data: percents,\n            scaleType: \"linear\",\n            min: 0,\n            max: PERCENT_MAX * (1 + X_PAD_SHARE),\n            tickInterval: Array.from({ length: X_TICK_STEPS + 1 }, (_, i) => (i * PERCENT_MAX) / X_TICK_STEPS),\n            valueFormatter: (v: number) => `${v} %`,\n            label: \"Population targeted, ranked by score (%)\",\n            height: 64,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            max: liftMax * (1 + Y_HEADROOM_SHARE),\n            width: 72,\n            label: \"Cumulative lift (model rate ÷ base rate)\",\n            valueFormatter: (v: number) => `${v.toFixed(1)}×`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        sx={{\n          \"& .MuiLineChart-line\": { strokeWidth: 3.5 },\n          \"& .MuiLineChart-mark\": { strokeWidth: 2.5 },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      >\n        <ChartsReferenceLine\n          y={NO_LIFT}\n          label=\"Random selection (lift 1×)\"\n          labelAlign=\"start\"\n          spacing={{ x: 10, y: 10 }}\n          labelStyle={{ fontSize: 15, fill: t.inkSoft }}\n          lineStyle={{ stroke: t.inkSoft, strokeWidth: 2, strokeDasharray: \"8 5\" }}\n        />\n        <KeyLiftLabels />\n      </LineChart>\n    </Box>\n  );\n}\n"}