{"spec_id":"polar-scatter","library":"muix","language":"javascript","code":"// anyplot.ai\n// polar-scatter: Polar Scatter Plot\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-24\n//# anyplot-orientation: square\n\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"polar-scatter · javascript · muix · anyplot.ai\";\nconst RING_COUNT = 4;\nconst SPOKE_STEP_DEG = 45;\nconst FULL_CIRCLE_DEG = 360;\nconst DEG_SYMBOL = \"°\";\nconst FILL_OPACITY = 0.72;\nconst MARKER_SIZE = 8;\nconst TITLE_HEIGHT = 74;\nconst LEGEND_HEIGHT = 40;\nconst CHART_MARGIN = { top: 14, bottom: 14, left: 14, right: 14 };\nconst LABEL_RADIUS_FACTOR = 1.065;\nconst DOMAIN_PAD_FACTOR = 1.11;\n\n// Columns: set these to your data's column names\nconst CATEGORY = \"Time of Day\"; // role: group\nconst BEARING = \"Wind Bearing (°)\"; // role: theta\nconst SPEED = \"Wind Speed (m/s)\"; // role: r\n\n// Data: replace this block with your own records\nconst POINTS_PER_GROUP = 30;\nconst MIN_SPEED_FLOOR = 0.5;\nconst SPEED_CEIL_CAP = 20;\nconst GROUP_SEEDS = [\n  { name: \"Morning\", meanBearing: 15, meanSpeed: 7, spread: 85 },\n  { name: \"Afternoon\", meanBearing: 105, meanSpeed: 13, spread: 90 },\n  { name: \"Evening\", meanBearing: 195, meanSpeed: 10, spread: 80 },\n  { name: \"Night\", meanBearing: 285, meanSpeed: 4, spread: 75 },\n];\n\nconst data: Array<Record<string, string | number>> = [];\nlet lcgState = 42;\nfor (const cfg of GROUP_SEEDS) {\n  for (let idx = 0; idx < POINTS_PER_GROUP; idx += 1) {\n    lcgState = (lcgState * 1664525 + 1013904223) % 4294967296;\n    const u1 = lcgState / 4294967296;\n    lcgState = (lcgState * 1664525 + 1013904223) % 4294967296;\n    const u2 = lcgState / 4294967296;\n    const bearing =\n      (((cfg.meanBearing + (u1 - 0.5) * cfg.spread) % FULL_CIRCLE_DEG) + FULL_CIRCLE_DEG) %\n      FULL_CIRCLE_DEG;\n    const speed = Math.min(\n      SPEED_CEIL_CAP,\n      Math.max(MIN_SPEED_FLOOR, cfg.meanSpeed + (u2 - 0.5) * cfg.meanSpeed),\n    );\n    data.push({\n      [CATEGORY]: cfg.name,\n      [BEARING]: Math.round(bearing * 100) / 100,\n      [SPEED]: Math.round(speed * 100) / 100,\n    });\n  }\n}\n\n// Plot: reads only data and the constants above\nconst categories: string[] = [];\nfor (const row of data) {\n  const cat = String(row[CATEGORY]);\n  if (!categories.includes(cat)) categories.push(cat);\n}\n\nconst rawMaxSpeed = Math.max(...data.map((r) => Number(r[SPEED])));\nconst rawStep = rawMaxSpeed / RING_COUNT;\nconst stepMag = 10 ** Math.floor(Math.log10(rawStep));\nconst stepNorm = rawStep / stepMag;\nconst ringStep = (stepNorm <= 1 ? 1 : stepNorm <= 2 ? 2 : stepNorm <= 5 ? 5 : 10) * stepMag;\nconst ringDecimals = Math.max(0, -Math.floor(Math.log10(ringStep) + 1e-9));\nconst maxRadius = ringStep * RING_COUNT;\nconst rings: number[] = [];\nfor (let k = 1; k <= RING_COUNT; k += 1) {\n  rings.push(Number((k * ringStep).toFixed(ringDecimals)));\n}\n\nconst spokeDegrees: number[] = [];\nfor (let deg = 0; deg < FULL_CIRCLE_DEG; deg += SPOKE_STEP_DEG) {\n  spokeDegrees.push(deg);\n}\n\n// Choose ring-label bearing at the centre of the 45° sector with fewest points\nconst sectorCount = FULL_CIRCLE_DEG / SPOKE_STEP_DEG;\nconst sectorCounts = new Array<number>(sectorCount).fill(0);\nfor (const row of data) {\n  const b = (((Number(row[BEARING]) % FULL_CIRCLE_DEG) + FULL_CIRCLE_DEG) % FULL_CIRCLE_DEG);\n  const sIdx = Math.min(sectorCount - 1, Math.floor(b / SPOKE_STEP_DEG));\n  sectorCounts[sIdx] += 1;\n}\nlet minSectorIdx = 0;\nfor (let s = 1; s < sectorCount; s += 1) {\n  if (sectorCounts[s] < sectorCounts[minSectorIdx]) {\n    minSectorIdx = s;\n  }\n}\nconst tickSpokeDeg = minSectorIdx * SPOKE_STEP_DEG + SPOKE_STEP_DEG / 2;\nconst tickSpokeRad = (tickSpokeDeg * Math.PI) / 180;\n\nconst speedUnitMatch = /\\(([^)]+)\\)/.exec(SPEED);\nconst speedUnit = speedUnitMatch ? speedUnitMatch[1] : \"\";\n\nconst labelRadius = maxRadius * LABEL_RADIUS_FACTOR;\nconst domainLimit = maxRadius * DOMAIN_PAD_FACTOR;\n\nconst seriesGroups = categories.map((cat, i) => {\n  const catRows = data.filter((r) => String(r[CATEGORY]) === cat);\n  const points = catRows.map((row, idx) => {\n    const bearingDeg = Number(row[BEARING]);\n    const radiusVal = Number(row[SPEED]);\n    const rad = (bearingDeg * Math.PI) / 180;\n    return {\n      id: `${cat}-${idx}`,\n      x: radiusVal * Math.sin(rad),\n      y: radiusVal * Math.cos(rad),\n    };\n  });\n\n  return {\n    type: \"scatter\" as const,\n    id: cat,\n    label: cat,\n    color: t.palette[i],\n    markerSize: MARKER_SIZE,\n    data: points,\n  };\n});\n\nfunction PolarGrid() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n\n  const cx = Number(xScale(0));\n  const cy = Number(yScale(0));\n\n  return (\n    <g>\n      {rings.map((r) => (\n        <circle\n          key={`ring-${r}`}\n          cx={cx}\n          cy={cy}\n          r={Math.abs(Number(xScale(r)) - cx)}\n          fill=\"none\"\n          stroke={t.grid}\n          strokeWidth={r === maxRadius ? 1.5 : 1}\n        />\n      ))}\n      {spokeDegrees.map((deg) => {\n        const rad = (deg * Math.PI) / 180;\n        const sx = maxRadius * Math.sin(rad);\n        const sy = maxRadius * Math.cos(rad);\n        const lx = labelRadius * Math.sin(rad);\n        const ly = labelRadius * Math.cos(rad);\n        return (\n          <g key={`spoke-${deg}`}>\n            <line\n              x1={cx}\n              y1={cy}\n              x2={xScale(sx)}\n              y2={yScale(sy)}\n              stroke={t.grid}\n              strokeWidth={1}\n            />\n            <text\n              x={xScale(lx)}\n              y={yScale(ly)}\n              fill={t.inkSoft}\n              fontSize={14}\n              fontWeight={deg % 90 === 0 ? 600 : 400}\n              textAnchor=\"middle\"\n              dominantBaseline=\"central\"\n            >\n              {`${deg}${DEG_SYMBOL}`}\n            </text>\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\n// Drawn after <ScatterPlot /> so the ring labels stay readable above the markers\nfunction RingLabels() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n\n  return (\n    <g>\n      {rings.map((r) => {\n        const tx = Number(xScale(r * Math.sin(tickSpokeRad)));\n        const ty = Number(yScale(r * Math.cos(tickSpokeRad)));\n        const rStr = r.toFixed(ringDecimals);\n        const tickText = speedUnit ? `${rStr} ${speedUnit}` : rStr;\n        const pillWidth = tickText.length * 8.2 + 12;\n        return (\n          <g key={`ring-label-${r}`}>\n            <rect\n              x={tx - pillWidth / 2}\n              y={ty - 11}\n              width={pillWidth}\n              height={22}\n              rx={4}\n              fill={t.pageBg}\n            />\n            <text\n              x={tx}\n              y={ty}\n              fill={t.inkSoft}\n              fontSize={14}\n              textAnchor=\"middle\"\n              dominantBaseline=\"central\"\n            >\n              {tickText}\n            </text>\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartSize = height - TITLE_HEIGHT - LEGEND_HEIGHT;\n\n  return (\n    <div\n      style={{\n        width,\n        height,\n        backgroundColor: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n        alignItems: \"center\",\n        boxSizing: \"border-box\",\n      }}\n    >\n      <div\n        style={{\n          height: TITLE_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 }}>\n          {`Angle: ${BEARING}, clockwise from 0${DEG_SYMBOL} at top  ·  Radius: ${SPEED}`}\n        </div>\n      </div>\n      <ChartsDataProvider\n        width={chartSize}\n        height={chartSize}\n        margin={CHART_MARGIN}\n        skipAnimation\n        xAxis={[{ scaleType: \"linear\", min: -domainLimit, max: domainLimit, position: \"none\" }]}\n        yAxis={[{ scaleType: \"linear\", min: -domainLimit, max: domainLimit, position: \"none\" }]}\n        series={seriesGroups}\n      >\n        <ChartsWrapper\n          legendPosition={{ vertical: \"bottom\", horizontal: \"center\" }}\n          sx={{ \"& .MuiScatterChart-marker\": { fillOpacity: FILL_OPACITY } }}\n        >\n          <ChartsLegend sx={{ fontSize: 15, color: t.inkSoft, gap: 3.5 }} />\n          <ChartsSurface>\n            <PolarGrid />\n            <ScatterPlot />\n            <RingLabels />\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}