{"spec_id":"precision-recall","library":"muix","language":"javascript","code":"// anyplot.ai\n// precision-recall: Precision-Recall Curve\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst UNIT_TICKS = Array.from({ length: 11 }, (_, i) => i / 10); // recall and precision live on 0–1\nconst AXIS_PAD = 0.02; // share of the 0–1 range kept free around the curves\nconst TITLE_H = 48;\nconst SUBTITLE_H = 28;\nconst LEGEND_H = 40;\n\n// Columns: set these to your data's column names\nconst IS_FRAUD = \"Fraud (1 = yes)\"; // role: y_true\nconst SCORES = [\"Gradient boosting\", \"Logistic regression\"]; // role: y_scores\n\n// Data: replace this block with your own records, one object per row\n// 600 card transactions (a 6 % fraud draw that yields 24 positives, 4 %, in this sample) scored\n// by two classifiers, predict_proba()-style outputs from a fixed-seed LCG with Box-Muller\n// normals mapped through a sigmoid\nlet lcgState = 42 >>> 0;\nconst draws = Array.from({ length: 600 * 5 }, () => {\n  lcgState = (Math.imul(lcgState, 1664525) + 1013904223) >>> 0;\n  return lcgState / 4294967296;\n});\nconst fraud = draws.slice(0, 600).map((u) => (u < 0.06 ? 1 : 0));\nconst normals = Array.from({ length: 1200 }, (_, k) => {\n  const u1 = Math.max(draws[600 + 2 * k], 1e-9);\n  return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * draws[601 + 2 * k]);\n});\nconst data = fraud.map((label, i) => ({\n  [IS_FRAUD]: label,\n  [SCORES[0]]: Math.round((1 / (1 + Math.exp(-(label === 1 ? 2.1 + normals[i] : -1.3 + normals[i])))) * 1e4) / 1e4,\n  [SCORES[1]]: Math.round((1 / (1 + Math.exp(-(label === 1 ? 0.9 + 1.3 * normals[600 + i] : -0.3 + 1.3 * normals[600 + i])))) * 1e4) / 1e4,\n}));\n\n// Plot: reads only data and the constants above\nconst labelled = data.filter((d) => d[IS_FRAUD] === 0 || d[IS_FRAUD] === 1);\nconst positives = labelled.filter((d) => d[IS_FRAUD] === 1).length;\nconst baseline = positives / labelled.length;\n\n// One precision-recall curve per score column: thresholds at every distinct score, highest first\nconst curves = SCORES.map((model) => {\n  const scored = labelled.filter((d) => Number.isFinite(d[model])).sort((a, b) => b[model] - a[model]);\n  const modelPositives = scored.filter((d) => d[IS_FRAUD] === 1).length;\n  const recall = [0];\n  const precision = [1];\n  let truePositives = 0;\n  let falsePositives = 0;\n  let i = 0;\n  while (i < scored.length) {\n    const score = scored[i][model];\n    while (i < scored.length && scored[i][model] === score) {\n      if (scored[i][IS_FRAUD] === 1) truePositives += 1;\n      else falsePositives += 1;\n      i += 1;\n    }\n    recall.push(truePositives / modelPositives);\n    precision.push(truePositives / (truePositives + falsePositives));\n  }\n  // Average precision, AP = sum over thresholds of (R_n - R_(n-1)) * P_n\n  let ap = 0;\n  for (let k = 1; k < recall.length; k++) ap += (recall[k] - recall[k - 1]) * precision[k];\n  return { model, recall, precision, ap };\n});\n\nconst TITLE = \"Fraud Detection · precision-recall · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${labelled.length} transactions · ${positives} positives (${(baseline * 100).toFixed(1)} %) · step curves through every score threshold`;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: TITLE_H, display: \"flex\", alignItems: \"flex-end\", justifyContent: \"center\", fontSize: 22, fontWeight: 600, color: t.ink }}>\n        {TITLE}\n      </div>\n      <div style={{ height: SUBTITLE_H, display: \"flex\", alignItems: \"center\", justifyContent: \"center\", fontSize: 15, color: t.inkSoft }}>\n        {SUBTITLE}\n      </div>\n      <LineChart\n        width={width}\n        height={height - TITLE_H - SUBTITLE_H - LEGEND_H}\n        skipAnimation\n        margin={{ top: 16, right: 48, bottom: 8, left: 16 }}\n        grid={{ horizontal: true, vertical: true }}\n        xAxis={curves.map((c, i) => ({\n          id: `recall-${i}`,\n          data: c.recall,\n          scaleType: \"linear\",\n          min: -AXIS_PAD,\n          max: 1 + AXIS_PAD,\n          tickInterval: UNIT_TICKS,\n          valueFormatter: (v) => v.toFixed(1),\n          position: i === 0 ? \"bottom\" : \"none\",\n          label: \"Recall\",\n          height: 64,\n          labelStyle: { fontSize: 16, fill: t.ink },\n          tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n        }))}\n        yAxis={[\n          {\n            min: -AXIS_PAD,\n            max: 1 + AXIS_PAD,\n            tickInterval: UNIT_TICKS,\n            valueFormatter: (v) => v.toFixed(1),\n            label: \"Precision\",\n            width: 72,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        series={curves.map((c, i) => ({\n          id: `model-${i}`,\n          xAxisId: `recall-${i}`,\n          data: c.precision,\n          label: `${c.model} (AP = ${c.ap.toFixed(2)})`,\n          color: t.palette[i],\n          curve: \"stepBefore\",\n          showMark: false,\n        }))}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"bottom\", horizontal: \"center\" },\n            sx: { fontSize: 15, color: t.inkSoft },\n          },\n        }}\n        sx={{\n          \"& .MuiLineChart-line\": { strokeWidth: 3 },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n        }}\n      >\n        <ChartsReferenceLine\n          y={baseline}\n          label={`Random classifier: precision = positive rate ${baseline.toFixed(3)}`}\n          labelAlign=\"start\"\n          spacing={{ x: 12, y: 10 }}\n          lineStyle={{ stroke: t.inkSoft, strokeDasharray: \"7 5\", strokeWidth: 2 }}\n          labelStyle={{ fontSize: 14, fill: t.inkSoft }}\n        />\n      </LineChart>\n    </div>\n  );\n}\n"}