{"spec_id":"roc-curve","library":"muix","language":"javascript","code":"// anyplot.ai\n// roc-curve: ROC Curve with AUC\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 86/100 | Updated: 2026-11-08\n//# anyplot-orientation: square\n\nimport { LineChart } from \"@mui/x-charts/LineChart\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst UNIT_TICKS = Array.from({ length: 11 }, (_, i) => i / 10); // both rates live on 0–1\nconst AXIS_PAD = 0.02; // share of the 0–1 range kept free around the curves\nconst RANDOM_AUC = 0.5; // the area under the diagonal of a random classifier\nconst TITLE_H = 48;\nconst SUBTITLE_H = 28;\nconst LEGEND_H = 44;\nconst X_AXIS_H = 64;\nconst Y_AXIS_W = 72;\nconst GAP = 24; // free space around the square drawing area, px\n\n// Columns: set these to your data's column names\nconst MODEL = \"Model\"; // role: extra\nconst FPR = \"False positive rate\"; // role: fpr\nconst TPR = \"True positive rate\"; // role: tpr\n\n// Data: replace this block with your own records, one object per row\n// Biopsy classification, 500 malignant and 500 benign samples scored by two models; each row is one\n// operating point of sklearn.metrics.roc_curve, threshold swept from the highest score down.\n// Fixed-seed LCG with Box-Muller normals; the forest separates the classes by 2.3 SD, the\n// logistic model by 1.15 SD.\nconst data = (() => {\n  let s = 42 >>> 0;\n  const rand = () => {\n    s = (Math.imul(1664525, s) + 1013904223) >>> 0;\n    return s / 4294967295;\n  };\n  const normal = (mean) => mean + Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n  return [\n    [\"Random Forest\", 2.3],\n    [\"Logistic Regression\", 1.15],\n  ].flatMap(([model, shift]) => {\n    const scored = [\n      ...Array.from({ length: 500 }, () => ({ score: normal(shift), positive: true })),\n      ...Array.from({ length: 500 }, () => ({ score: normal(0), positive: false })),\n    ].sort((a, b) => b.score - a.score);\n    let tp = 0;\n    let fp = 0;\n    return [\n      { [MODEL]: model, [FPR]: 0, [TPR]: 0 },\n      ...scored.map((d) => {\n        if (d.positive) tp += 1;\n        else fp += 1;\n        return { [MODEL]: model, [FPR]: fp / 500, [TPR]: tp / 500 };\n      }),\n    ];\n  });\n})();\n\n// Plot: reads only data and the constants above\n// One curve per model, its operating points sorted by FPR, AUC by the trapezoidal rule\nconst models = [...new Set(data.map((d) => d[MODEL]))];\nconst curves = models.map((model) => {\n  const points = data\n    .filter((d) => d[MODEL] === model && Number.isFinite(d[FPR]) && Number.isFinite(d[TPR]))\n    .sort((a, b) => a[FPR] - b[FPR] || a[TPR] - b[TPR]);\n  const auc = points.slice(1).reduce((s, p, i) => s + ((p[FPR] - points[i][FPR]) * (p[TPR] + points[i][TPR])) / 2, 0);\n  return { model, fpr: points.map((p) => p[FPR]), tpr: points.map((p) => p[TPR]), auc };\n});\nconst pointsPerCurve = Math.max(...curves.map((c) => c.fpr.length));\n\nconst TITLE = \"roc-curve · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${models.length} classifiers · up to ${pointsPerCurve} operating points per curve · AUC by the trapezoidal rule`;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartH = height - TITLE_H - SUBTITLE_H - LEGEND_H;\n  const side = Math.min(width - Y_AXIS_W, chartH - X_AXIS_H) - 2 * GAP;\n  const sideX = (width - Y_AXIS_W - side) / 2;\n  const sideY = (chartH - X_AXIS_H - side) / 2;\n  const unitAxis = {\n    scaleType: \"linear\",\n    min: -AXIS_PAD,\n    max: 1 + AXIS_PAD,\n    tickInterval: UNIT_TICKS,\n    valueFormatter: (v) => v.toFixed(1),\n  };\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={chartH}\n        skipAnimation\n        margin={{ top: sideY, bottom: sideY, left: sideX, right: sideX }}\n        grid={{ horizontal: true, vertical: true }}\n        xAxis={[\n          ...curves.map((c, i) => ({\n            ...unitAxis,\n            id: `fpr-${i}`,\n            data: c.fpr,\n            position: i === 0 ? \"bottom\" : \"none\",\n            label: FPR,\n            height: X_AXIS_H,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          })),\n          { ...unitAxis, id: \"diagonal\", data: [0, 1], position: \"none\" },\n        ]}\n        yAxis={[\n          {\n            ...unitAxis,\n            label: TPR,\n            width: Y_AXIS_W,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        series={[\n          ...curves.map((c, i) => ({\n            id: `model-${i}`,\n            xAxisId: `fpr-${i}`,\n            data: c.tpr,\n            label: `${c.model} (AUC = ${c.auc.toFixed(2)})`,\n            color: t.palette[i],\n            curve: \"linear\",\n            showMark: false,\n          })),\n          {\n            id: \"diagonal\",\n            xAxisId: \"diagonal\",\n            data: [0, 1],\n            label: `Random classifier (AUC = ${RANDOM_AUC.toFixed(2)})`,\n            color: t.inkSoft,\n            curve: \"linear\",\n            showMark: false,\n          },\n        ]}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"bottom\", horizontal: \"center\" },\n            sx: { fontSize: 15, color: t.ink },\n          },\n        }}\n        sx={{\n          '& .MuiLineChart-line[data-series^=\"model\"]': { strokeWidth: 3 },\n          '& .MuiLineChart-line[data-series=\"diagonal\"]': { strokeWidth: 2, strokeDasharray: \"10 6\" },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n        }}\n      />\n    </div>\n  );\n}\n"}