{"spec_id":"scatter-pitch-events","library":"muix","language":"javascript","code":"// anyplot.ai\n// scatter-pitch-events: Soccer Pitch Event Map\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\n// FIFA pitch geometry in metres\nconst PITCH_LENGTH = 105;\nconst PITCH_WIDTH = 68;\nconst CENTRE_CIRCLE_RADIUS = 9.15;\nconst PENALTY_AREA_DEPTH = 16.5;\nconst PENALTY_AREA_WIDTH = 40.32;\nconst GOAL_AREA_DEPTH = 5.5;\nconst GOAL_AREA_WIDTH = 18.32;\nconst PENALTY_SPOT_DISTANCE = 11;\nconst GOAL_WIDTH = 7.32;\nconst GOAL_DEPTH = 2;\nconst CORNER_ARC_RADIUS = 1;\nconst RUN_OFF = 3; // metres shown around the pitch, room for the goals\n// One shape per event type, by order of first appearance (unit radius, centred on the origin)\nconst MARKER_SHAPES = [\n  \"M -1 0 A 1 1 0 1 0 1 0 A 1 1 0 1 0 -1 0 Z\",\n  `M ${Array.from({ length: 10 }, (_, i) => {\n    const a = (i * Math.PI) / 5 - Math.PI / 2;\n    const r = i % 2 === 0 ? 1.25 : 0.5;\n    return `${(r * Math.cos(a)).toFixed(3)} ${(r * Math.sin(a)).toFixed(3)}`;\n  }).join(\" L \")} Z`,\n  \"M 0 -1.15 L 1 0.6 L -1 0.6 Z\",\n  \"M 0 -1.2 L 0.85 0 L 0 1.2 L -0.85 0 Z\",\n  \"M -0.9 -0.9 L 0.9 -0.9 L 0.9 0.9 L -0.9 0.9 Z\",\n  \"M 0 1.15 L 1 -0.6 L -1 -0.6 Z\",\n];\nconst FILLED_OUTCOME = \"Successful\"; // the spec's outcome levels: this one is drawn filled, any other hollow\nconst MARKER_RADIUS = 8; // px\n// The spec asks for a white pitch with contrasting lines in both themes, so the pitch keeps the\n// light theme's elevated surface and soft ink in either theme instead of flipping with the page\nconst PITCH_SURFACE = \"#FFFDF6\";\nconst PITCH_INK = \"#4A4A44\";\nconst RUN_OFF_TINT = 0.15; // opacity of the ink wash that sets the theme-adaptive run-off apart from the pitch\n\n// Columns: set these to your data's column names\nconst X = \"x (m)\"; // role: x\nconst Y = \"y (m)\"; // role: y\nconst EVENT = \"Event type\"; // role: event_type\nconst OUTCOME = \"Outcome\"; // role: outcome\nconst END_X = \"End x (m)\"; // role: end_x\nconst END_Y = \"End y (m)\"; // role: end_y\n\n// Data: replace this block with your own records, one object per row\n// Synthetic match segment: passes and shots carry an end position, tackles and\n// interceptions do not.\nconst data = (() => {\n  let s = 42;\n  const rng = () => {\n    s = (Math.imul(1664525, s) + 1013904223) >>> 0;\n    return s / 4294967296;\n  };\n  const rows = [];\n  const event = (type, x, y, ok, endX = null, endY = null) =>\n    rows.push({\n      [X]: Number(x.toFixed(1)),\n      [Y]: Number(y.toFixed(1)),\n      [EVENT]: type,\n      [OUTCOME]: ok ? \"Successful\" : \"Unsuccessful\",\n      [END_X]: endX === null ? null : Number(endX.toFixed(1)),\n      [END_Y]: endY === null ? null : Number(endY.toFixed(1)),\n    });\n  for (let i = 0; i < 48; i += 1) {\n    const x = rng() * 100 + 2.5;\n    const y = rng() * 63 + 2.5;\n    const dx = (rng() - 0.2) * 22;\n    const dy = (rng() - 0.5) * 16;\n    const endX = Math.max(2, Math.min(103, x + dx));\n    const endY = Math.max(2, Math.min(66, y + dy));\n    event(\"Pass\", x, y, rng() > 0.22, endX, endY);\n  }\n  for (let i = 0; i < 10; i += 1) {\n    const x = 70 + rng() * 30;\n    const y = 17 + rng() * 34;\n    const endX = 102 + rng() * 3;\n    const endY = 30.34 + rng() * 7.32;\n    event(\"Shot\", x, y, rng() > 0.75, endX, endY);\n  }\n  for (let i = 0; i < 22; i += 1) {\n    const x = rng() * 105;\n    const y = rng() * 68;\n    event(\"Tackle\", x, y, rng() > 0.35);\n  }\n  for (let i = 0; i < 18; i += 1) {\n    const x = rng() * 105;\n    const y = rng() * 68;\n    event(\"Interception\", x, y, rng() > 0.12);\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst types = [...new Set(data.map((d) => d[EVENT]))];\nconst outcomes = [...new Set(data.map((d) => d[OUTCOME]))];\nconst events = data.map((d, i) => {\n  const k = types.indexOf(d[EVENT]);\n  return {\n    id: `event-${i}`,\n    x: d[X],\n    y: d[Y],\n    endX: d[END_X],\n    endY: d[END_Y],\n    color: t.palette[k],\n    shape: MARKER_SHAPES[k],\n    typeIndex: k,\n    filled: d[OUTCOME] === FILLED_OUTCOME,\n  };\n});\n// Arrows go wherever a row carries an end position\nconst arrows = events.filter((e) => e.endX !== null && e.endY !== null);\nconst arrowTypes = types.filter((_, k) => arrows.some((a) => a.typeIndex === k));\n\nconst penaltyArcHalf = Math.sqrt(CENTRE_CIRCLE_RADIUS ** 2 - (PENALTY_AREA_DEPTH - PENALTY_SPOT_DISTANCE) ** 2);\nconst corners = [\n  [0, 0, 1, 1],\n  [PITCH_LENGTH, 0, -1, 1],\n  [0, PITCH_WIDTH, 1, -1],\n  [PITCH_LENGTH, PITCH_WIDTH, -1, -1],\n]; // corner x, corner y, and the inward direction along each touchline\n\nconst TITLE = \"scatter-pitch-events · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${data.length} events · ${PITCH_LENGTH} m × ${PITCH_WIDTH} m pitch · arrows run to the end position of ${arrowTypes.map((s) => s.toLowerCase()).join(\" and \")} events`;\nconst HEADER_HEIGHT = 72;\nconst LEGEND_HEIGHT = 48;\nconst chartWidth = window.ANYPLOT_SIZE.width;\nconst chartHeight = window.ANYPLOT_SIZE.height - HEADER_HEIGHT - LEGEND_HEIGHT;\n\n// Equal px per metre on both axes keeps the centre circle round and the pitch at 105:68\nconst domainLength = PITCH_LENGTH + 2 * RUN_OFF;\nconst domainWidth = PITCH_WIDTH + 2 * RUN_OFF;\nconst areaHeight = Math.min(chartHeight - 16, ((chartWidth - 48) * domainWidth) / domainLength);\nconst areaWidth = (areaHeight * domainLength) / domainWidth;\nconst marginX = (chartWidth - areaWidth) / 2;\nconst marginY = (chartHeight - areaHeight) / 2;\n\nconst line = { fill: \"none\", stroke: PITCH_INK, strokeWidth: 2 };\n\nfunction PitchMarkings() {\n  const { left, top, width, height } = useDrawingArea();\n  const xs = useXScale();\n  const ys = useYScale();\n  const k = xs(1) - xs(0); // px per metre\n  const midY = PITCH_WIDTH / 2;\n  return (\n    <g>\n      <rect x={left} y={top} width={width} height={height} fill={t.elevatedBg} />\n      <rect x={left} y={top} width={width} height={height} fill={t.inkSoft} fillOpacity={RUN_OFF_TINT} />\n      <rect x={xs(0)} y={ys(PITCH_WIDTH)} width={PITCH_LENGTH * k} height={PITCH_WIDTH * k} fill={PITCH_SURFACE} />\n      <rect {...line} x={xs(0)} y={ys(PITCH_WIDTH)} width={PITCH_LENGTH * k} height={PITCH_WIDTH * k} />\n      <line {...line} x1={xs(PITCH_LENGTH / 2)} y1={ys(0)} x2={xs(PITCH_LENGTH / 2)} y2={ys(PITCH_WIDTH)} />\n      <circle {...line} cx={xs(PITCH_LENGTH / 2)} cy={ys(midY)} r={CENTRE_CIRCLE_RADIUS * k} />\n      <circle cx={xs(PITCH_LENGTH / 2)} cy={ys(midY)} r={3.5} fill={PITCH_INK} />\n      {[0, PITCH_LENGTH].map((goalLine) => {\n        const inward = goalLine === 0 ? 1 : -1;\n        const spotX = goalLine + inward * PENALTY_SPOT_DISTANCE;\n        const boxX = goalLine + inward * PENALTY_AREA_DEPTH;\n        return (\n          <g key={`end-${goalLine}`}>\n            <rect\n              {...line}\n              x={xs(Math.min(goalLine, boxX))}\n              y={ys(midY + PENALTY_AREA_WIDTH / 2)}\n              width={PENALTY_AREA_DEPTH * k}\n              height={PENALTY_AREA_WIDTH * k}\n            />\n            <rect\n              {...line}\n              x={xs(Math.min(goalLine, goalLine + inward * GOAL_AREA_DEPTH))}\n              y={ys(midY + GOAL_AREA_WIDTH / 2)}\n              width={GOAL_AREA_DEPTH * k}\n              height={GOAL_AREA_WIDTH * k}\n            />\n            <rect\n              {...line}\n              fill={PITCH_SURFACE}\n              strokeWidth={3}\n              x={xs(Math.min(goalLine, goalLine - inward * GOAL_DEPTH))}\n              y={ys(midY + GOAL_WIDTH / 2)}\n              width={GOAL_DEPTH * k}\n              height={GOAL_WIDTH * k}\n            />\n            <circle cx={xs(spotX)} cy={ys(midY)} r={3} fill={PITCH_INK} />\n            {/* Penalty arc: the part of the 9.15 m circle around the spot that lies outside the box */}\n            <path\n              {...line}\n              d={`M ${xs(boxX)} ${ys(midY + penaltyArcHalf)} A ${CENTRE_CIRCLE_RADIUS * k} ${CENTRE_CIRCLE_RADIUS * k} 0 0 ${goalLine === 0 ? 1 : 0} ${xs(boxX)} ${ys(midY - penaltyArcHalf)}`}\n            />\n          </g>\n        );\n      })}\n      {corners.map(([cx, cy, dx, dy]) => (\n        <path\n          key={`corner-${cx}-${cy}`}\n          {...line}\n          d={`M ${xs(cx + dx * CORNER_ARC_RADIUS)} ${ys(cy)} A ${CORNER_ARC_RADIUS * k} ${CORNER_ARC_RADIUS * k} 0 0 ${-dx * dy > 0 ? 1 : 0} ${xs(cx)} ${ys(cy + dy * CORNER_ARC_RADIUS)}`}\n        />\n      ))}\n    </g>\n  );\n}\n\nfunction EventLayer() {\n  const xs = useXScale();\n  const ys = useYScale();\n  return (\n    <g>\n      <defs>\n        {types.map((type, k) => (\n          <marker\n            key={`head-${type}`}\n            id={`pitch-head-${k}`}\n            viewBox=\"0 0 10 10\"\n            refX={9}\n            refY={5}\n            markerWidth={11}\n            markerHeight={11}\n            markerUnits=\"userSpaceOnUse\"\n            orient=\"auto\"\n          >\n            <path d=\"M 0 0 L 10 5 L 0 10 Z\" fill={t.palette[k]} />\n          </marker>\n        ))}\n      </defs>\n      {arrows.map((a) => (\n        <line\n          key={`arrow-${a.id}`}\n          x1={xs(a.x)}\n          y1={ys(a.y)}\n          x2={xs(a.endX)}\n          y2={ys(a.endY)}\n          stroke={a.color}\n          strokeOpacity={a.filled ? 0.8 : 0.55}\n          strokeWidth={a.filled ? 1.8 : 1.4}\n          strokeDasharray={a.filled ? undefined : \"5 4\"}\n          markerEnd={`url(#pitch-head-${a.typeIndex})`}\n        />\n      ))}\n      {events.map((e) => (\n        <path\n          key={e.id}\n          d={e.shape}\n          transform={`translate(${xs(e.x)} ${ys(e.y)}) scale(${MARKER_RADIUS})`}\n          vectorEffect=\"non-scaling-stroke\"\n          fill={e.filled ? e.color : PITCH_SURFACE}\n          stroke={e.filled ? PITCH_SURFACE : e.color}\n          strokeWidth={e.filled ? 1 : 2.2}\n        />\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div\n        style={{\n          height: HEADER_HEIGHT,\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 6,\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</div>\n      </div>\n      <ChartsDataProvider\n        width={chartWidth}\n        height={chartHeight}\n        margin={{ top: marginY, bottom: marginY, left: marginX, right: marginX }}\n        skipAnimation\n        xAxis={[{ id: \"x\", scaleType: \"linear\", min: -RUN_OFF, max: PITCH_LENGTH + RUN_OFF, position: \"none\" }]}\n        yAxis={[{ id: \"y\", scaleType: \"linear\", min: -RUN_OFF, max: PITCH_WIDTH + RUN_OFF, position: \"none\" }]}\n      >\n        <ChartsSurface>\n          <PitchMarkings />\n          <EventLayer />\n        </ChartsSurface>\n      </ChartsDataProvider>\n      <div\n        style={{\n          height: LEGEND_HEIGHT,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 26,\n          fontSize: 16,\n          color: t.ink,\n        }}\n      >\n        {types.map((type, k) => (\n          <span key={`legend-${type}`} style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <svg width={24} height={24}>\n              <path d={MARKER_SHAPES[k]} transform={`translate(12 12) scale(${MARKER_RADIUS})`} fill={t.palette[k]} />\n            </svg>\n            {type}\n          </span>\n        ))}\n        <span style={{ width: 1, height: 24, background: t.grid }} />\n        {outcomes.map((outcome) => (\n          <span key={`legend-${outcome}`} style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <svg width={24} height={24}>\n              <path\n                d={MARKER_SHAPES[0]}\n                transform={`translate(12 12) scale(${MARKER_RADIUS})`}\n                vectorEffect=\"non-scaling-stroke\"\n                fill={outcome === FILLED_OUTCOME ? t.inkSoft : \"none\"}\n                stroke={t.inkSoft}\n                strokeWidth={2}\n              />\n            </svg>\n            {outcome}\n          </span>\n        ))}\n      </div>\n    </div>\n  );\n}\n"}