{"spec_id":"calibration-curve","library":"muix","language":"javascript","code":"// anyplot.ai\n// calibration-curve: Calibration Curve\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-23\n\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { BarChart } from \"@mui/x-charts/BarChart\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Columns: set these to your data's column names\nconst Y_TRUE = \"Fraction of Positives\"; // role: y_true\nconst Y_PROB = \"Logistic regression (screening)\"; // role: y_prob\nconst Y_PROB_B = \"Boosted trees, uncalibrated\"; // role: extra\n\n// Data: replace this block with your own records, one object per row\n// Predicted disease risk from a well-calibrated logistic-regression screening\n// model and an overconfident, uncalibrated boosted-trees model against\n// ground-truth binary diagnoses.\nconst data = (() => {\n  function mulberry32(seed: number) {\n    return function random() {\n      seed = (seed + 0x6d2b79f5) | 0;\n      let x = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n      x = (x + Math.imul(x ^ (x >>> 7), 61 | x)) ^ x;\n      return ((x ^ (x >>> 14)) >>> 0) / 4294967296;\n    };\n  }\n\n  function gaussian(random: () => number): number {\n    const u = Math.max(random(), 1e-9);\n    const v = random();\n    return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);\n  }\n\n  const clamp01 = (v: number) => Math.min(1, Math.max(0, v));\n  const logit = (p: number) => Math.log(p / (1 - p));\n  const sigmoid = (z: number) => 1 / (1 + Math.exp(-z));\n\n  const nSamples = 3000;\n  const random = mulberry32(42);\n  const overconfidenceScale = 2.4;\n\n  const trueRisk = Array.from({ length: nSamples }, () => random());\n  const yTrueArr = trueRisk.map((risk) => (random() < risk ? 1 : 0));\n  const predAArr = trueRisk.map((risk) => clamp01(risk + 0.05 * gaussian(random)));\n  const predBArr = trueRisk.map((risk) =>\n    sigmoid(logit(clamp01(risk) * 0.998 + 0.001) * overconfidenceScale),\n  );\n\n  return yTrueArr.map((truth, i) => ({\n    [Y_TRUE]: truth,\n    [Y_PROB]: predAArr[i],\n    [Y_PROB_B]: predBArr[i],\n  }));\n})();\n\n// Plot: reads only data and the constants above\nconst NUM_BINS = 10;\nconst yTrue = data.map((d) => d[Y_TRUE]);\n\n// Per model: bin counts, mean predicted probability and fraction of positives\n// per bin, then ECE (bin-weighted |fraction − mean prediction|) and Brier score\nconst models = [Y_PROB, Y_PROB_B].map((col) => {\n  const pred = data.map((d) => d[col]);\n  const count = Array(NUM_BINS).fill(0);\n  const sumPred = Array(NUM_BINS).fill(0);\n  const sumTrue = Array(NUM_BINS).fill(0);\n  pred.forEach((p, i) => {\n    const idx = Math.min(NUM_BINS - 1, Math.floor(p * NUM_BINS));\n    count[idx] += 1;\n    sumPred[idx] += p;\n    sumTrue[idx] += yTrue[i];\n  });\n  const points = count\n    .map((n, b) => (n > 0 ? { x: sumPred[b] / n, y: sumTrue[b] / n, n } : null))\n    .filter((pt) => pt !== null);\n  const ece = points.reduce((acc, pt) => acc + (pt.n / pred.length) * Math.abs(pt.y - pt.x), 0);\n  const brier = pred.reduce((acc, p, i) => acc + (p - yTrue[i]) ** 2, 0) / pred.length;\n  return { label: col, count, points, ece, brier };\n});\n\n// Shared x axis: every model's own (mean prediction) x values plus the 0/1\n// diagonal endpoints; each series is null away from its own points\nconst xValues = [...new Set([0, 1, ...models.flatMap((m) => m.points.map((pt) => pt.x))])].sort(\n  (a, b) => a - b,\n);\nconst modelSeries = models.map((m) => {\n  const yAt = new Map(m.points.map((pt) => [pt.x, pt.y]));\n  return xValues.map((x) => yAt.get(x) ?? null);\n});\nconst diagonalSeries = xValues.map((x) => (x === 0 || x === 1 ? x : null));\n\nconst binLabels = Array.from(\n  { length: NUM_BINS },\n  (_, i) => `${Math.round((i / NUM_BINS) * 100)}–${Math.round(((i + 1) / NUM_BINS) * 100)}%`,\n);\n\nconst TITLE_HEIGHT = 78;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartAreaHeight = height - TITLE_HEIGHT;\n  const mainHeight = Math.round(chartAreaHeight * 0.62);\n  const histHeight = chartAreaHeight - mainHeight;\n\n  return (\n    <Box\n      sx={{\n        width,\n        height,\n        bgcolor: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n        paddingTop: \"16px\",\n      }}\n    >\n      <Typography\n        sx={{\n          color: t.ink,\n          fontSize: 22,\n          fontWeight: 500,\n          textAlign: \"center\",\n          lineHeight: 1.2,\n        }}\n      >\n        calibration-curve · javascript · muix · anyplot.ai\n      </Typography>\n      <Typography\n        sx={{\n          color: t.inkSoft,\n          fontSize: 14,\n          textAlign: \"center\",\n          lineHeight: 1.4,\n          marginTop: \"4px\",\n        }}\n      >\n        {models.map((m) => `${m.label} — ECE ${m.ece.toFixed(3)}, Brier ${m.brier.toFixed(3)}`).join(\"   ·   \")}\n      </Typography>\n\n      <LineChart\n        width={width}\n        height={mainHeight}\n        skipAnimation\n        disableHitArea\n        colors={t.palette}\n        xAxis={[\n          {\n            height: 60,\n            data: xValues,\n            scaleType: \"linear\",\n            min: 0,\n            max: 1,\n            label: \"Mean Predicted Probability\",\n            valueFormatter: (v: number) => `${Math.round(v * 100)}%`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            width: 84,\n            min: 0,\n            max: 1,\n            label: Y_TRUE,\n            valueFormatter: (v: number) => `${Math.round(v * 100)}%`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={[\n          {\n            id: \"diagonal\",\n            data: diagonalSeries,\n            label: \"Perfect calibration\",\n            color: t.ink,\n            showMark: false,\n            connectNulls: true,\n            curve: \"linear\",\n          },\n          ...models.map((m, i) => ({\n            id: `model${i}`,\n            data: modelSeries[i],\n            label: m.label,\n            color: t.palette[i],\n            showMark: true,\n            connectNulls: true,\n            curve: \"linear\" as const,\n          })),\n        ]}\n        margin={{ left: 50, right: 40, top: 16, bottom: 16 }}\n        sx={{\n          \"& .MuiChartsLegend-root\": { color: t.ink },\n          \"& .MuiChartsLegend-label\": { fontSize: \"14px\", color: t.ink },\n          '& [data-series^=\"model\"].MuiLineChart-line': { strokeWidth: 3 },\n          '& [data-series=\"diagonal\"].MuiLineChart-line': { strokeWidth: 2, strokeDasharray: \"8 5\" },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n        }}\n      >\n        <ChartsGrid horizontal />\n      </LineChart>\n\n      <BarChart\n        width={width}\n        height={histHeight}\n        skipAnimation\n        disableHitArea\n        hideLegend\n        borderRadius={2}\n        xAxis={[\n          {\n            height: 56,\n            scaleType: \"band\",\n            data: binLabels,\n            label: \"Predicted Probability Bin\",\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            width: 84,\n            label: \"Count\",\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={models.map((m, i) => ({ data: m.count, label: m.label, color: t.palette[i] }))}\n        margin={{ left: 50, right: 40, top: 8, bottom: 20 }}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n        }}\n      />\n    </Box>\n  );\n}\n"}