{"spec_id":"logistic-regression","library":"muix","language":"javascript","code":"// anyplot.ai\n// logistic-regression: Logistic Regression Curve Plot\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 89/100 | Updated: 2026-10-24\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\nconst { width, height } = window.ANYPLOT_SIZE;\n\n// Constants\nconst PROBABILITY_AXIS_LABEL = \"Probability\";\nconst DECISION_THRESHOLD = 0.5;\nconst X_PAD_FRAC = 0.03;\nconst Y_PAD_FRAC = 0.08;\nconst JITTER_SPREAD = 0.14;\nconst CURVE_STEPS = 200;\nconst GD_ITERATIONS = 600;\nconst GD_LR = 0.5;\nconst Z95 = 1.96;\nconst POINT_ALPHA_HEX = \"99\"; // ~0.60 alpha\n\nconst SEMANTIC_COLORS: Record<number, string> = {\n  0: t.palette[4],\n  1: t.palette[0],\n};\n\n// Columns: set these to your data's column names\nconst SCORE = \"Customer engagement score\"; // role: x\nconst OUTCOME = \"Converted\"; // role: y\nconst OUTCOME_LABEL = \"Outcome class\"; // role: class_label\n\n// Data: replace this block with your own records\nconst N_POINTS = 180;\nlet seed = 42 >>> 0;\nconst rawScores: number[] = [];\nfor (let i = 0; i < N_POINTS; i++) {\n  seed = (Math.imul(1664525, seed) + 1013904223) >>> 0;\n  rawScores.push(Math.round((seed / 4294967296) * 1000) / 10);\n}\n\nconst rawConverted: number[] = [];\nfor (let i = 0; i < N_POINTS; i++) {\n  seed = (Math.imul(1664525, seed) + 1013904223) >>> 0;\n  const u = seed / 4294967296;\n  const pTrue = 1 / (1 + Math.exp(-(0.09 * (rawScores[i] - 55))));\n  rawConverted.push(u < pTrue ? 1 : 0);\n}\n\nconst data: Array<Record<string, number | string>> = [];\nfor (let i = 0; i < N_POINTS; i++) {\n  const yBin = rawConverted[i];\n  data.push({\n    [SCORE]: rawScores[i],\n    [OUTCOME]: yBin,\n    [OUTCOME_LABEL]: yBin === 1 ? \"Converted (y = 1)\" : \"Not converted (y = 0)\",\n  });\n}\n\n// Plot: reads only data and the constants above\nlet jitterSeed = 1337 >>> 0;\nconst jitteredRows = data.map((r, idx) => {\n  jitterSeed = (Math.imul(1664525, jitterSeed) + 1013904223) >>> 0;\n  const jitter = (jitterSeed / 4294967296 - 0.5) * JITTER_SPREAD;\n  const yBin = Number(r[OUTCOME]);\n  return {\n    id: idx,\n    x: Number(r[SCORE]),\n    yBin,\n    yJittered: yBin + jitter,\n    label: String(r[OUTCOME_LABEL]),\n  };\n});\n\n// Binary outcome: 0 and 1 map straight to their fixed colors and labels\nconst outcomeBins = [0, 1];\nconst classLabelMap: Record<number, string> = {};\nfor (const b of outcomeBins) {\n  classLabelMap[b] = jitteredRows.find((r) => r.yBin === b)?.label ?? `${OUTCOME} = ${b}`;\n}\n\n// Fit logistic regression by batch gradient descent on standardized x\nconst nObs = jitteredRows.length;\nconst xs = jitteredRows.map((r) => r.x);\nconst ys = jitteredRows.map((r) => r.yBin);\nconst xMean = xs.reduce((a, b) => a + b, 0) / nObs;\nconst xStd = Math.sqrt(xs.reduce((a, b) => a + (b - xMean) ** 2, 0) / nObs);\nconst xn = xs.map((v) => (v - xMean) / xStd);\n\nlet b0 = 0;\nlet b1 = 0;\nfor (let iter = 0; iter < GD_ITERATIONS; iter++) {\n  let grad0 = 0;\n  let grad1 = 0;\n  for (let i = 0; i < nObs; i++) {\n    const p = 1 / (1 + Math.exp(-(b0 + b1 * xn[i])));\n    const err = p - ys[i];\n    grad0 += err;\n    grad1 += err * xn[i];\n  }\n  b0 -= (GD_LR * grad0) / nObs;\n  b1 -= (GD_LR * grad1) / nObs;\n}\n\n// Observed Fisher information covariance (X'WX)^-1\nlet info00 = 0;\nlet info01 = 0;\nlet info11 = 0;\nfor (let i = 0; i < nObs; i++) {\n  const p = 1 / (1 + Math.exp(-(b0 + b1 * xn[i])));\n  const w = p * (1 - p);\n  info00 += w;\n  info01 += w * xn[i];\n  info11 += w * xn[i] * xn[i];\n}\nconst det = info00 * info11 - info01 * info01;\nconst varB0 = info11 / det;\nconst varB1 = info00 / det;\nconst covB01 = -info01 / det;\n\nconst midpointX = xMean + (-b0 / b1) * xStd;\nlet correctCount = 0;\nfor (let i = 0; i < nObs; i++) {\n  const p = 1 / (1 + Math.exp(-(b0 + b1 * xn[i])));\n  const pred = p >= DECISION_THRESHOLD ? 1 : 0;\n  if (pred === ys[i]) correctCount++;\n}\nconst accuracy = correctCount / nObs;\n\nconst rawXMin = Math.min(...xs);\nconst rawXMax = Math.max(...xs);\nconst xSpan = rawXMax - rawXMin;\nconst xDataMin = rawXMin - xSpan * X_PAD_FRAC;\nconst xDataMax = rawXMax + xSpan * X_PAD_FRAC;\nconst yAxisMin = -Y_PAD_FRAC;\nconst yAxisMax = 1 + Y_PAD_FRAC;\n\nconst curveXs: number[] = [];\nconst curveY: number[] = [];\nconst ciLower: number[] = [];\nconst ciUpper: number[] = [];\n\nfor (let i = 0; i < CURVE_STEPS; i++) {\n  const xVal = xDataMin + (i / (CURVE_STEPS - 1)) * (xDataMax - xDataMin);\n  const z = (xVal - xMean) / xStd;\n  const eta = b0 + b1 * z;\n  const se = Math.sqrt(Math.max(0, varB0 + 2 * z * covB01 + z * z * varB1));\n  curveXs.push(xVal);\n  curveY.push(1 / (1 + Math.exp(-eta)));\n  ciLower.push(1 / (1 + Math.exp(-(eta - Z95 * se))));\n  ciUpper.push(1 / (1 + Math.exp(-(eta + Z95 * se))));\n}\n\nconst scatterSeries = outcomeBins.map((bin, idx) => {\n  const rows = jitteredRows.filter((r) => r.yBin === bin);\n  return {\n    type: \"scatter\" as const,\n    id: `class-${idx}`,\n    data: rows.map((r) => ({\n      x: r.x,\n      y: r.yJittered,\n      id: `${idx}-${r.id}`,\n    })),\n    label: classLabelMap[bin],\n    color: `${SEMANTIC_COLORS[bin]}${POINT_ALPHA_HEX}`,\n    markerSize: 7,\n    xAxisId: \"engagement\",\n    yAxisId: \"probability\",\n  };\n});\n\nfunction LogisticOverlay() {\n  const xScale = useXScale(\"engagement\") as (v: number) => number;\n  const yScale = useYScale(\"probability\") as (v: number) => number;\n\n  const upperPts = curveXs.map((x, i) => [xScale(x), yScale(ciUpper[i])]);\n  const lowerPts = curveXs.map((x, i) => [xScale(x), yScale(ciLower[i])]);\n  const bandPts = [...upperPts, ...lowerPts.slice().reverse()];\n  const bandD =\n    bandPts\n      .map((p, i) => `${i === 0 ? \"M\" : \"L\"}${p[0].toFixed(1)},${p[1].toFixed(1)}`)\n      .join(\" \") + \" Z\";\n\n  const curveD = curveXs\n    .map((x, i) => `${i === 0 ? \"M\" : \"L\"}${xScale(x).toFixed(1)},${yScale(curveY[i]).toFixed(1)}`)\n    .join(\" \");\n\n  const markerX = xScale(midpointX);\n  const markerY = yScale(DECISION_THRESHOLD);\n  const labelX = markerX - 68;\n  const labelY = yScale(0.62);\n\n  return (\n    <g>\n      <path d={bandD} fill={t.ink} fillOpacity={0.14} stroke=\"none\" />\n      <path\n        d={curveD}\n        fill=\"none\"\n        stroke={t.ink}\n        strokeWidth={3}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      />\n      <circle\n        cx={markerX}\n        cy={markerY}\n        r={5.5}\n        fill={t.pageBg}\n        stroke={t.ink}\n        strokeWidth={2}\n      />\n      <text x={labelX} y={labelY} fontSize={14} fill={t.inkSoft} textAnchor=\"end\">\n        <tspan x={labelX} dy={0}>{`Midpoint ≈ ${midpointX.toFixed(1)}`}</tspan>\n        <tspan x={labelX} dy={19}>{`Accuracy at p=${DECISION_THRESHOLD}: ${(accuracy * 100).toFixed(0)}%`}</tspan>\n      </text>\n    </g>\n  );\n}\n\nconst TITLE = \"logistic-regression · javascript · muix · anyplot.ai\";\nconst TITLE_HEIGHT = 64;\n\nconst LEGEND_ITEMS = [\n  ...outcomeBins.map((b) => ({\n    type: \"circle\" as const,\n    color: SEMANTIC_COLORS[b],\n    label: classLabelMap[b],\n  })),\n  { type: \"line\" as const, color: t.ink, label: \"Fitted probability (95% CI)\" },\n];\n\n// Legend sits in the plot's empty upper-left area (few conversions at low scores)\nconst MARGIN = { top: 24, right: 64, bottom: 20, left: 20 };\nconst X_AXIS_HEIGHT = 60;\nconst Y_AXIS_WIDTH = 76;\nconst LEGEND_TOP_PROB = 0.88;\nconst plotHeight = height - TITLE_HEIGHT - MARGIN.top - MARGIN.bottom - X_AXIS_HEIGHT;\nconst legendTop =\n  TITLE_HEIGHT +\n  MARGIN.top +\n  (plotHeight * (yAxisMax - LEGEND_TOP_PROB)) / (yAxisMax - yAxisMin);\nconst legendLeft = MARGIN.left + Y_AXIS_WIDTH + 24;\n\nexport default function Chart() {\n  return (\n    <div style={{ width, height, backgroundColor: t.pageBg, position: \"relative\" }}>\n      <div\n        style={{\n          height: TITLE_HEIGHT,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          fontSize: 22,\n          fontWeight: 600,\n          color: t.ink,\n        }}\n      >\n        {TITLE}\n      </div>\n      <div\n        style={{\n          position: \"absolute\",\n          top: legendTop,\n          left: legendLeft,\n          zIndex: 1,\n          display: \"flex\",\n          flexDirection: \"column\",\n          gap: 6,\n          alignItems: \"flex-start\",\n        }}\n      >\n        {LEGEND_ITEMS.map((item) => (\n          <div key={item.label} style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            {item.type === \"circle\" ? (\n              <span\n                style={{\n                  width: 10,\n                  height: 10,\n                  borderRadius: \"50%\",\n                  backgroundColor: item.color,\n                  flexShrink: 0,\n                }}\n              />\n            ) : (\n              <span\n                style={{\n                  width: 18,\n                  height: 3,\n                  backgroundColor: item.color,\n                  flexShrink: 0,\n                }}\n              />\n            )}\n            <span style={{ fontSize: 14, color: t.ink }}>{item.label}</span>\n          </div>\n        ))}\n      </div>\n      <ChartsContainer\n        width={width}\n        height={height - TITLE_HEIGHT}\n        skipAnimation\n        margin={MARGIN}\n        series={scatterSeries}\n        xAxis={[\n          {\n            id: \"engagement\",\n            scaleType: \"linear\",\n            data: curveXs,\n            min: xDataMin,\n            max: xDataMax,\n            height: X_AXIS_HEIGHT,\n            label: SCORE,\n            tickNumber: 6,\n            valueFormatter: (v: number | null) =>\n              v === null ? \"\" : `${Math.round(v)}`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"probability\",\n            min: yAxisMin,\n            max: yAxisMax,\n            width: Y_AXIS_WIDTH,\n            label: PROBABILITY_AXIS_LABEL,\n            tickInterval: [0, 0.2, 0.4, 0.6, 0.8, 1],\n            valueFormatter: (v: number | null) => (v != null ? v.toFixed(1) : \"\"),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n      >\n        <ChartsGrid horizontal />\n        <ScatterPlot skipAnimation />\n        <LogisticOverlay />\n        <ChartsXAxis axisId=\"engagement\" />\n        <ChartsYAxis axisId=\"probability\" />\n        <ChartsReferenceLine\n          y={DECISION_THRESHOLD}\n          axisId=\"probability\"\n          label={`Decision threshold (p = ${DECISION_THRESHOLD})`}\n          labelAlign=\"start\"\n          labelStyle={{ fill: t.inkSoft, fontSize: 14 }}\n          lineStyle={{ stroke: t.inkSoft, strokeDasharray: \"8 5\", strokeWidth: 1.5 }}\n        />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}