{"spec_id":"scatter-complex-plane","library":"muix","language":"javascript","code":"// anyplot.ai\n// scatter-complex-plane: Complex Plane Visualization (Argand Diagram)\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 90/100 | Updated: 2026-11-08\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 { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { useXScale, useYScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst UNIT_RADIUS = 1; // the unit circle |z| = 1\nconst LABEL_ROOM_SHARE = 0.4; // room beyond the outermost point for its annotation, as a share of its modulus\nconst TICK_TARGET = 3; // about this many ticks on each half-axis\nconst NICE_STEPS = [1, 2, 2.5, 5, 10]; // tick steps per power of ten\nconst LABEL_GAP = 22; // px between a point and its annotation, outward along the point's phase\nconst ROW_GAP = 22; // px between the rectangular and the polar row of an annotation\nconst BLOCK_LIFT = 26; // px from a point's height to its annotation's centre, away from the real axis\nconst MARKER_RADIUS = 9; // px\nconst UNIT_TICK_NUDGE = 14; // px a tick label on the unit circle moves outward along its axis, off the circle\nconst ZERO_OFFSET = [14, 20]; // px from the origin to the \"0\" label, across and along the real axis\nconst MINUS = \"−\"; // one minus sign for every number on the plot\n\n// Columns: set these to your data's column names\nconst LABEL = \"Label\"; // role: label\nconst REAL = \"Real part\"; // role: real\nconst IMAGINARY = \"Imaginary part\"; // role: imaginary\nconst GROUP = \"Group\"; // role: extra\n\n// Data: replace this block with your own records, one object per row\n// The three cube roots of unity (solutions of z³ = 1) beside three arbitrary complex numbers.\nconst data = [\n  { [LABEL]: \"z1\", [REAL]: 1, [IMAGINARY]: 0, [GROUP]: \"Cube roots of unity\" },\n  { [LABEL]: \"z2\", [REAL]: -0.5, [IMAGINARY]: Math.sqrt(3) / 2, [GROUP]: \"Cube roots of unity\" },\n  { [LABEL]: \"z3\", [REAL]: -0.5, [IMAGINARY]: -Math.sqrt(3) / 2, [GROUP]: \"Cube roots of unity\" },\n  { [LABEL]: \"w1\", [REAL]: 1.7, [IMAGINARY]: 1.0, [GROUP]: \"Arbitrary points\" },\n  { [LABEL]: \"w2\", [REAL]: -1.4, [IMAGINARY]: 1.8, [GROUP]: \"Arbitrary points\" },\n  { [LABEL]: \"w3\", [REAL]: 0.9, [IMAGINARY]: -1.9, [GROUP]: \"Arbitrary points\" },\n];\n\n// Plot: reads only data and the constants above\nconst groups = [...new Set(data.map((d) => d[GROUP]))];\nconst groupColor = Object.fromEntries(groups.map((g, i) => [g, t.palette[i]]));\n\n// One symmetric extent on both axes keeps px per unit equal, so the unit circle stays round\nconst reach = Math.max(UNIT_RADIUS, ...data.map((d) => Math.max(Math.abs(d[REAL]), Math.abs(d[IMAGINARY]))));\nconst extent = reach * (1 + LABEL_ROOM_SHARE);\nconst rawStep = reach / TICK_TARGET;\nconst magnitude = 10 ** Math.floor(Math.log10(rawStep));\nconst tickStep = NICE_STEPS.find((s) => s * magnitude >= rawStep) * magnitude;\nconst ticks = Array.from(\n  { length: 2 * Math.floor(extent / tickStep) + 1 },\n  (_, k) => Number(((k - Math.floor(extent / tickStep)) * tickStep).toFixed(6)),\n);\n// A tick label on the unit circle moves outward along its axis, so the circle does not run through it\nconst offAxisTicks = ticks\n  .filter((v) => v !== 0)\n  .map((v) => ({ v, text: `${v}`.replace(\"-\", MINUS), nudge: Math.abs(v) === UNIT_RADIUS ? Math.sign(v) * UNIT_TICK_NUDGE : 0 }));\n\nconst points = data.map((d) => {\n  const re = d[REAL];\n  const im = d[IMAGINARY];\n  return {\n    label: d[LABEL],\n    group: d[GROUP],\n    re,\n    im,\n    rect: `${d[LABEL]} = ${re.toFixed(2).replace(\"-\", MINUS)} ${im < 0 ? MINUS : \"+\"} ${Math.abs(im).toFixed(2)}i`,\n    polar: `|z| = ${Math.hypot(re, im).toFixed(2)} ∠ ${((Math.atan2(im, re) * 180) / Math.PI).toFixed(0).replace(\"-\", MINUS)}°`,\n  };\n});\n\n// A page-coloured outline keeps text legible where it crosses the circle, grid or a vector\nconst halo = { stroke: t.pageBg, strokeWidth: 4, paintOrder: \"stroke\", strokeLinejoin: \"round\" } as const;\n\nconst TITLE = \"scatter-complex-plane · javascript · muix · anyplot.ai\";\nconst HEADER_HEIGHT = 64;\nconst LEGEND_HEIGHT = 40;\nconst chartWidth = window.ANYPLOT_SIZE.width;\nconst chartHeight = window.ANYPLOT_SIZE.height - HEADER_HEIGHT - LEGEND_HEIGHT;\nconst side = Math.min(chartWidth, chartHeight) - 32;\nconst margin = {\n  top: (chartHeight - side) / 2,\n  bottom: (chartHeight - side) / 2,\n  left: (chartWidth - side) / 2,\n  right: (chartWidth - side) / 2,\n};\n\n// Annotation placement in px from the origin: each block sits just beyond its point along the point's\n// phase, on the side facing away from the origin, so it clears its own vector and the unit circle\nconst pxPerUnit = side / (2 * extent);\nconst annotations = points.map((p) => {\n  const theta = Math.atan2(p.im, p.re);\n  const cos = Math.cos(theta);\n  const sin = Math.sin(theta);\n  const r = Math.hypot(p.re, p.im) * pxPerUnit + LABEL_GAP;\n  const anchor = cos > 0.3 ? \"start\" : cos < -0.3 ? \"end\" : \"middle\";\n  const dir = anchor === \"start\" ? 1 : anchor === \"end\" ? -1 : 0;\n  const x = cos * r;\n  const y = -sin * r + (sin < 0 ? BLOCK_LIFT : -BLOCK_LIFT);\n  // A neighbouring vector that would run through the block, on the side the text extends to, pushes the block past it\n  const crossings = points\n    .filter((q) => q !== p && q.im !== 0)\n    .flatMap((q) => [y - BLOCK_LIFT, y + BLOCK_LIFT].map((ry) => ({ s: ry / (-q.im * pxPerUnit), ry, q })))\n    .filter(({ s }) => s > 0 && s <= 1)\n    .map(({ s, q }) => s * q.re * pxPerUnit)\n    .filter((cx) => dir !== 0 && (cx - x) * dir > 0);\n  const pushed = crossings.length ? (dir > 0 ? Math.max(...crossings) : Math.min(...crossings)) + dir * LABEL_GAP : x;\n  return { x: pushed, y, anchor };\n});\n\n// The origin's \"0\" goes into the quadrant whose bisector lies furthest in angle from every vector\nconst angleGap = (a: number, b: number) => Math.abs(((a - b + 3 * Math.PI) % (2 * Math.PI)) - Math.PI);\nconst zeroQuadrant = [\n  [1, 1],\n  [-1, 1],\n  [-1, -1],\n  [1, -1],\n]\n  .map(([sx, sy]) => ({ sx, sy, room: Math.min(...points.map((q) => angleGap(Math.atan2(sy, sx), Math.atan2(q.im, q.re)))) }))\n  .reduce((best, q) => (q.room > best.room ? q : best));\n\nfunction PlaneAxes() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const area = useDrawingArea();\n  const zeroX = xScale(0);\n  const zeroY = yScale(0);\n  const right = area.left + area.width;\n  const bottom = area.top + area.height;\n  return (\n    <g>\n      <circle\n        cx={zeroX}\n        cy={zeroY}\n        r={Math.abs(xScale(UNIT_RADIUS) - zeroX)}\n        fill=\"none\"\n        stroke={t.inkSoft}\n        strokeWidth={2}\n        strokeDasharray=\"9 8\"\n      />\n      <line x1={area.left} y1={zeroY} x2={right} y2={zeroY} stroke={t.ink} strokeWidth={2} />\n      <line x1={zeroX} y1={area.top} x2={zeroX} y2={bottom} stroke={t.ink} strokeWidth={2} />\n      {offAxisTicks.map(({ v }) => (\n        <g key={`tick-${v}`}>\n          <line x1={xScale(v)} y1={zeroY - 7} x2={xScale(v)} y2={zeroY + 7} stroke={t.ink} strokeWidth={1.5} />\n          <line x1={zeroX - 7} y1={yScale(v)} x2={zeroX + 7} y2={yScale(v)} stroke={t.ink} strokeWidth={1.5} />\n        </g>\n      ))}\n      <text x={right - 4} y={zeroY - 14} textAnchor=\"end\" fontSize={17} fontWeight={600} fill={t.ink}>\n        {REAL}\n      </text>\n      <text x={zeroX + 14} y={area.top + 18} textAnchor=\"start\" fontSize={17} fontWeight={600} fill={t.ink}>\n        {IMAGINARY}\n      </text>\n    </g>\n  );\n}\n\nfunction Vectors() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const zeroX = xScale(0);\n  const zeroY = yScale(0);\n  return (\n    <g>\n      <defs>\n        {groups.map((g, i) => (\n          <marker\n            key={`head-${i}`}\n            id={`complex-plane-head-${i}`}\n            viewBox=\"0 0 10 10\"\n            refX={10}\n            refY={5}\n            markerWidth={14}\n            markerHeight={14}\n            markerUnits=\"userSpaceOnUse\"\n            orient=\"auto\"\n          >\n            <path d=\"M0,0 L10,5 L0,10 Z\" fill={groupColor[g]} />\n          </marker>\n        ))}\n      </defs>\n      {points.map((p) => {\n        const px = xScale(p.re);\n        const py = yScale(p.im);\n        const length = Math.hypot(px - zeroX, py - zeroY);\n        // The head ends at the marker's rim, so it stays visible above the point\n        const tipX = px - ((px - zeroX) / length) * (MARKER_RADIUS + 1);\n        const tipY = py - ((py - zeroY) / length) * (MARKER_RADIUS + 1);\n        return (\n          <line\n            key={`vector-${p.label}`}\n            x1={zeroX}\n            y1={zeroY}\n            x2={tipX}\n            y2={tipY}\n            stroke={groupColor[p.group]}\n            strokeWidth={2.5}\n            markerEnd={`url(#complex-plane-head-${groups.indexOf(p.group)})`}\n          />\n        );\n      })}\n    </g>\n  );\n}\n\n// Tick labels sit above the vectors, so their halo keeps them legible where a vector passes\nfunction TickLabels() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const zeroX = xScale(0);\n  const zeroY = yScale(0);\n  return (\n    <g {...halo}>\n      {offAxisTicks.map(({ v, text, nudge }) => (\n        <g key={`tick-label-${v}`}>\n          <text x={xScale(v) + nudge} y={zeroY + 28} textAnchor=\"middle\" fontSize={17} fill={t.inkSoft}>\n            {text}\n          </text>\n          <text x={zeroX - 14} y={yScale(v) - nudge} textAnchor=\"end\" dominantBaseline=\"central\" fontSize={17} fill={t.inkSoft}>\n            {`${text}i`}\n          </text>\n        </g>\n      ))}\n      <text\n        x={zeroX + zeroQuadrant.sx * ZERO_OFFSET[0]}\n        y={zeroY - zeroQuadrant.sy * ZERO_OFFSET[1]}\n        textAnchor={zeroQuadrant.sx > 0 ? \"start\" : \"end\"}\n        dominantBaseline=\"central\"\n        fontSize={17}\n        fill={t.inkSoft}\n      >\n        0\n      </text>\n    </g>\n  );\n}\n\nfunction Annotations() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g {...halo}>\n      {points.map((p, i) => {\n        const { x, y, anchor } = annotations[i];\n        return (\n          <g key={`note-${p.label}`}>\n            <text x={xScale(0) + x} y={yScale(0) + y - ROW_GAP / 2} textAnchor={anchor} dominantBaseline=\"central\" fontSize={18} fontWeight={600} fill={t.ink}>\n              {p.rect}\n            </text>\n            <text x={xScale(0) + x} y={yScale(0) + y + ROW_GAP / 2} textAnchor={anchor} dominantBaseline=\"central\" fontSize={17} fill={t.inkSoft}>\n              {p.polar}\n            </text>\n          </g>\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          alignItems: \"center\",\n          justifyContent: \"center\",\n          fontSize: 22,\n          fontWeight: 600,\n          color: t.ink,\n        }}\n      >\n        {TITLE}\n      </div>\n      <ChartsDataProvider\n        width={chartWidth}\n        height={chartHeight}\n        margin={margin}\n        skipAnimation\n        series={groups.map((g, i) => ({\n          type: \"scatter\" as const,\n          id: `group-${i}`,\n          label: g,\n          color: groupColor[g],\n          markerSize: MARKER_RADIUS,\n          data: points.filter((p) => p.group === g).map((p) => ({ id: p.label, x: p.re, y: p.im })),\n        }))}\n        xAxis={[{ id: \"real\", scaleType: \"linear\", min: -extent, max: extent, tickInterval: ticks, position: \"none\" }]}\n        yAxis={[{ id: \"imaginary\", scaleType: \"linear\", min: -extent, max: extent, tickInterval: ticks, position: \"none\" }]}\n      >\n        <ChartsWrapper legendPosition={{ vertical: \"top\", horizontal: \"center\" }} legendDirection=\"horizontal\">\n          <ChartsLegend sx={{ fontSize: 16, color: t.ink, gap: 4 }} />\n          <ChartsSurface\n            sx={{\n              \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n              \"& .MuiScatterChart-marker\": { stroke: t.pageBg, strokeWidth: 2.5 },\n            }}\n          >\n            <ChartsGrid vertical horizontal />\n            <PlaneAxes />\n            <Vectors />\n            <TickLabels />\n            <ScatterPlot />\n            <Annotations />\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}