{"spec_id":"line-win-probability","library":"muix","language":"javascript","code":"// anyplot.ai\n// line-win-probability: Win Probability Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 89/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\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst EVEN = 0.5; // even odds: the reference line and the boundary between the two team fills\nconst PROB_TICKS = [0, 0.25, 0.5, 0.75, 1]; // the full probability domain\nconst PERIOD_LENGTH = 45; // minutes per half of a football match; a marker is drawn at every period end inside the game\nconst PERIOD_LABEL = \"Half time\";\n\n// Columns: set these to your data's column names\nconst MINUTE = \"Match time (min)\"; // role: game_time\nconst WIN_PROB = \"Home win probability\"; // role: win_probability\nconst EVENT = \"Event\"; // role: event\nconst HOME = \"Harwick Town\"; // role: extra\nconst AWAY = \"Millbrook Rovers\"; // role: extra\n\n// Data: replace this block with your own records, one object per row\n// Minute-by-minute model probability of a home win in a 90-minute match, with the running score\n// of each team: the away side scores early, the home side equalises and wins it late.\nconst data = (() => {\n  let s = 42;\n  const rand = () => {\n    s = (Math.imul(1664525, s) + 1013904223) | 0;\n    return (s >>> 0) / 0x100000000;\n  };\n  const fullTime = 90;\n  const goals = {\n    19: { side: \"away\", wp: 0.26, scorer: \"Lindqvist\" },\n    58: { side: \"home\", wp: 0.54, scorer: \"Okafor\" },\n    84: { side: \"home\", wp: 0.88, scorer: \"Mensah\" },\n  };\n  // The range the model moves in at each score (home-away)\n  const bands = { \"0-0\": [0.05, 0.95], \"0-1\": [0.11, 0.5], \"1-1\": [0.42, 0.67], \"2-1\": [0.81, 0.97] };\n  let wp = 0.5;\n  let home = 0;\n  let away = 0;\n  return Array.from({ length: fullTime + 1 }, (_, minute) => {\n    const goal = goals[minute];\n    const left = fullTime - minute;\n    if (goal) {\n      if (goal.side === \"home\") home += 1;\n      else away += 1;\n      wp = goal.wp;\n    } else if (left === 0) {\n      wp = home > away ? 1 : 0; // the final whistle settles it: a draw is not a home win\n    } else if (minute > 0) {\n      // Swings and the pull towards even odds shrink with the time left, and a lead firms up towards its result\n      const [lo, hi] = bands[`${home}-${away}`];\n      const share = left / fullTime;\n      const lead = Math.sign(home - away);\n      const firming = lead === 0 ? 0 : ((lead > 0 ? 1 : 0) - wp) / (left + 1);\n      const next = wp + (rand() - 0.5) * 0.055 * Math.sqrt(share) + (0.5 - wp) * 0.018 * share + firming;\n      wp = Math.max(lead < 0 ? 0 : lo, Math.min(lead > 0 ? 1 : hi, next));\n    }\n    return {\n      [MINUTE]: minute,\n      [WIN_PROB]: Math.round(wp * 1000) / 1000,\n      [EVENT]: goal ? `Goal · ${goal.scorer}` : null,\n      [HOME]: home,\n      [AWAY]: away,\n    };\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst rows = [...data].sort((a, b) => a[MINUTE] - b[MINUTE]);\nconst last = rows[rows.length - 1];\nconst xMin = rows[0][MINUTE];\nconst xMax = last[MINUTE];\n\n// Where the line crosses even odds, a point at exactly EVEN is inserted, so each team's fill ends at the crossing\nconst points = [];\nrows.forEach((d, i) => {\n  const prev = rows[i - 1];\n  if (prev && prev[WIN_PROB] != null && d[WIN_PROB] != null) {\n    const da = prev[WIN_PROB] - EVEN;\n    const db = d[WIN_PROB] - EVEN;\n    if (da * db < 0) points.push({ x: prev[MINUTE] + (da / (da - db)) * (d[MINUTE] - prev[MINUTE]), p: EVEN });\n  }\n  points.push({ x: d[MINUTE], p: d[WIN_PROB] });\n});\nconst xs = points.map((p) => p.x);\nconst homeAhead = points.map((p) => (p.p != null && p.p >= EVEN ? p.p : null));\nconst awayAhead = points.map((p) => (p.p != null && p.p <= EVEN ? p.p : null));\n\nconst HOME_COLOR = t.palette[0];\nconst AWAY_COLOR = t.palette[1];\n\n// An event takes the colour of the team whose score rose on its row; its label sits left of the swing,\n// at the new level, where the line arrives from the level before the event\nconst events = rows\n  .map((d, i) => ({ d, prev: rows[i - 1] ?? d }))\n  .filter(({ d }) => d[EVENT] != null && d[WIN_PROB] != null)\n  .map(({ d, prev }) => ({\n    x: d[MINUTE],\n    p: d[WIN_PROB],\n    color: d[HOME] > prev[HOME] ? HOME_COLOR : d[AWAY] > prev[AWAY] ? AWAY_COLOR : t.inkSoft,\n    text: `${d[MINUTE]}' ${d[EVENT]} (${d[HOME]}–${d[AWAY]})`,\n  }));\nconst periodEnds = Array.from({ length: Math.ceil(xMax / PERIOD_LENGTH) }, (_, k) => (k + 1) * PERIOD_LENGTH).filter(\n  (m) => m > xMin && m < xMax,\n);\n\nconst TITLE = \"line-win-probability · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `Final score: ${HOME} ${last[HOME]} – ${last[AWAY]} ${AWAY} · ${rows.length} model updates over ${xMax - xMin} minutes`;\nconst HEADER_H = 80;\nconst LEGEND_H = 44;\n\nfunction EventMarks() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g>\n      {events.map((e) => (\n        <g key={e.text}>\n          <circle cx={xScale(e.x)} cy={yScale(e.p)} r={7} fill={e.color} stroke={t.pageBg} strokeWidth={2.5} />\n          <text\n            x={xScale(e.x) - 16}\n            y={yScale(e.p)}\n            textAnchor=\"end\"\n            dominantBaseline=\"middle\"\n            fontSize={15}\n            fontWeight={600}\n            fill={t.ink}\n          >\n            {e.text}\n          </text>\n        </g>\n      ))}\n    </g>\n  );\n}\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: HEADER_H, padding: \"16px 40px 0 112px\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.25 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, marginTop: 6 }}>{SUBTITLE}</div>\n      </div>\n      <LineChart\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        skipAnimation\n        grid={{ horizontal: true }}\n        margin={{ top: 12, right: 48, bottom: 16, left: 24 }}\n        xAxis={[\n          {\n            data: xs,\n            scaleType: \"linear\",\n            min: xMin,\n            max: xMax,\n            tickNumber: 7,\n            valueFormatter: (v: number) => `${Math.round(v)}'`,\n            label: MINUTE,\n            height: 64,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: PROB_TICKS[0],\n            max: PROB_TICKS[PROB_TICKS.length - 1],\n            tickInterval: PROB_TICKS,\n            valueFormatter: (v: number) => `${Math.round(v * 100)}%`,\n            label: WIN_PROB,\n            width: 84,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={[\n          {\n            id: \"home\",\n            data: homeAhead,\n            label: `${HOME} (home) ahead`,\n            color: HOME_COLOR,\n            area: true,\n            baseline: EVEN,\n            curve: \"linear\",\n            showMark: false,\n            valueFormatter: (v: number | null) => (v == null ? \"\" : `${(v * 100).toFixed(1)}%`),\n          },\n          {\n            id: \"away\",\n            data: awayAhead,\n            label: `${AWAY} (away) ahead`,\n            color: AWAY_COLOR,\n            area: true,\n            baseline: EVEN,\n            curve: \"linear\",\n            showMark: false,\n            valueFormatter: (v: number | null) => (v == null ? \"\" : `${(v * 100).toFixed(1)}%`),\n          },\n        ]}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"top\", horizontal: \"end\" },\n            sx: { fontSize: 16, color: t.ink, columnGap: 3, pr: 5 },\n          },\n        }}\n        sx={{\n          \"& .MuiLineChart-area\": { fillOpacity: 0.32 },\n          \"& .MuiLineChart-line\": { strokeWidth: 3 },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      >\n        {periodEnds.map((m) => (\n          <ChartsReferenceLine\n            key={m}\n            x={m}\n            label={PERIOD_LABEL}\n            labelAlign=\"start\"\n            spacing={{ x: 8, y: 8 }}\n            labelStyle={{ fontSize: 15, fill: t.inkSoft }}\n            lineStyle={{ stroke: t.inkSoft, strokeDasharray: \"4 4\", strokeWidth: 1.5 }}\n          />\n        ))}\n        <ChartsReferenceLine y={EVEN} lineStyle={{ stroke: t.inkSoft, strokeWidth: 2.5 }} />\n        <EventMarks />\n      </LineChart>\n    </div>\n  );\n}\n"}