{"spec_id":"polar-line","library":"muix","language":"javascript","code":"// anyplot.ai\n// polar-line: Polar Line Plot\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 86/100 | Updated: 2026-10-24\n//# anyplot-orientation: square\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\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-line · javascript · muix · anyplot.ai\";\nconst FULL_CIRCLE_DEG = 360;\nconst SPOKE_STEP_DEG = 45;\nconst DEG_SYMBOL = \"°\";\nconst RING_COUNT = 5;\nconst MARKER_SIZE = 4;\nconst HEADER_HEIGHT = 64;\nconst FOOTER_HEIGHT = 56;\nconst CHART_MARGIN = 36;\nconst DOMAIN_PAD_FACTOR = 1.18;\nconst LABEL_RADIUS_FACTOR = 1.09;\n\n// Columns: set these to your data's column names\nconst SERIES_NAME = \"Antenna Type\"; // role: group\nconst AZIMUTH = \"Azimuth (°)\"; // role: theta\nconst GAIN = \"Normalized gain\"; // role: r\n\n// Data: replace this block with your own records\nconst ANGLE_STEP_DEG = 15;\n\nconst data: Array<Record<string, string | number>> = [];\nfor (let deg = 0; deg < FULL_CIRCLE_DEG; deg += ANGLE_STEP_DEG) {\n  const rad = (deg * Math.PI) / 180;\n  const omniVal =\n    Math.round((0.78 + 0.05 * Math.cos(3 * rad) + 0.03 * Math.cos(7 * rad)) * 1000) / 1000;\n  data.push({\n    [SERIES_NAME]: \"Omnidirectional dipole\",\n    [AZIMUTH]: deg,\n    [GAIN]: omniVal,\n  });\n}\nfor (let deg = 0; deg < FULL_CIRCLE_DEG; deg += ANGLE_STEP_DEG) {\n  const rad = (deg * Math.PI) / 180;\n  const cosVal = Math.cos(rad);\n  const mainLobe = Math.pow(Math.max(0, cosVal), 6);\n  const backLobe = 0.18 * Math.pow(Math.max(0, -cosVal), 10);\n  const yagiVal = Math.round(Math.min(1, 0.06 + 0.94 * mainLobe + backLobe) * 1000) / 1000;\n  data.push({\n    [SERIES_NAME]: \"Directional Yagi\",\n    [AZIMUTH]: deg,\n    [GAIN]: yagiVal,\n  });\n}\n\n// Plot: reads only data and the constants above\nconst seriesNames: string[] = [];\nfor (const row of data) {\n  const sName = String(row[SERIES_NAME]);\n  if (!seriesNames.includes(sName)) seriesNames.push(sName);\n}\n\nconst rawMaxGain = Math.max(...data.map((r) => Number(r[GAIN])));\nconst rawStep = rawMaxGain / 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 gainMax = 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 degreeTicks: number[] = [];\nfor (let deg = 0; deg < FULL_CIRCLE_DEG; deg += SPOKE_STEP_DEG) {\n  degreeTicks.push(deg);\n}\n\nconst seriesGroups = seriesNames.map((name, idx) => {\n  const groupRows = data\n    .filter((r) => String(r[SERIES_NAME]) === name)\n    .sort((a, b) => Number(a[AZIMUTH]) - Number(b[AZIMUTH]));\n  const color = t.palette[idx];\n  const points = groupRows.map((row) => {\n    const deg = Number(row[AZIMUTH]);\n    const gain = Number(row[GAIN]);\n    const angle = ((deg - 90) * Math.PI) / 180;\n    return {\n      id: `${name}-${deg}`,\n      deg,\n      gain,\n      angle,\n      x: gain * Math.cos(angle),\n      y: -gain * Math.sin(angle),\n    };\n  });\n  return { label: name, color, points };\n});\n\nconst domainLimit = gainMax * DOMAIN_PAD_FACTOR;\nconst labelRadiusVal = gainMax * LABEL_RADIUS_FACTOR;\n\nconst series = seriesGroups.map((group) => ({\n  type: \"scatter\" as const,\n  id: group.label,\n  label: group.label,\n  color: group.color,\n  markerSize: MARKER_SIZE,\n  data: group.points,\n}));\n\nfunction PolarLayer() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n\n  const cx = Number(xScale(0));\n  const cy = Number(yScale(0));\n  const midRingY = Number(yScale(rings[Math.floor(rings.length / 2)]));\n  const azimuthLabelX = cx + 32;\n  const azimuthLabelY = Number(yScale(labelRadiusVal));\n\n  return (\n    <g>\n      {rings.map((level) => (\n        <circle\n          key={`ring-${level}`}\n          cx={cx}\n          cy={cy}\n          r={Math.abs(Number(xScale(level)) - cx)}\n          fill=\"none\"\n          stroke={t.grid}\n          strokeWidth={level === gainMax ? 2 : 1}\n          strokeOpacity={level === gainMax ? 1 : 0.65}\n        />\n      ))}\n\n      {degreeTicks.map((deg) => {\n        const angle = ((deg - 90) * Math.PI) / 180;\n        const ox = Number(xScale(gainMax * Math.cos(angle)));\n        const oy = Number(yScale(-gainMax * Math.sin(angle)));\n        const lx = Number(xScale(labelRadiusVal * Math.cos(angle)));\n        const ly = Number(yScale(-labelRadiusVal * Math.sin(angle)));\n        const cos = Math.cos(angle);\n        const sin = Math.sin(angle);\n        const anchor = cos > 0.3 ? \"start\" : cos < -0.3 ? \"end\" : \"middle\";\n        const baseline = sin > 0.5 ? \"hanging\" : sin < -0.5 ? \"auto\" : \"central\";\n        const isCardinal = deg % 90 === 0;\n        return (\n          <g key={`spoke-${deg}`}>\n            <line x1={cx} y1={cy} x2={ox} y2={oy} stroke={t.grid} strokeWidth={1} />\n            <text\n              x={lx}\n              y={ly}\n              fill={isCardinal ? t.ink : t.inkSoft}\n              fontSize={isCardinal ? 17 : 14}\n              fontWeight={isCardinal ? 700 : 500}\n              textAnchor={anchor}\n              dominantBaseline={baseline}\n            >\n              {`${deg}${DEG_SYMBOL}`}\n            </text>\n          </g>\n        );\n      })}\n\n      {rings.map((level) => {\n        const ty = Number(yScale(level));\n        const label = level.toFixed(ringDecimals);\n        const pillWidth = label.length * 8.5 + 12;\n        return (\n          <g key={`tick-${level}`}>\n            <rect x={cx + 8} y={ty - 11} width={pillWidth} height={22} rx={4} fill={t.pageBg} />\n            <text\n              x={cx + 14}\n              y={ty}\n              fill={t.inkSoft}\n              fontSize={14}\n              textAnchor=\"start\"\n              dominantBaseline=\"central\"\n            >\n              {label}\n            </text>\n          </g>\n        );\n      })}\n\n      <g transform={`translate(${cx + 58}, ${midRingY}) rotate(-90)`}>\n        <rect x={-62} y={-11} width={124} height={22} rx={4} fill={t.pageBg} />\n        <text\n          x={0}\n          y={0}\n          fill={t.inkSoft}\n          fontSize={14}\n          fontWeight={600}\n          textAnchor=\"middle\"\n          dominantBaseline=\"central\"\n        >\n          {GAIN}\n        </text>\n      </g>\n\n      <text\n        x={azimuthLabelX}\n        y={azimuthLabelY}\n        fill={t.inkSoft}\n        fontSize={14}\n        fontWeight={600}\n        textAnchor=\"start\"\n        dominantBaseline=\"auto\"\n      >\n        {`${AZIMUTH}, clockwise`}\n      </text>\n\n      {seriesGroups.map((group) => {\n        const polyPoints = group.points.map((p) => `${xScale(p.x)},${yScale(p.y)}`).join(\" \");\n        return (\n          <polygon\n            key={`poly-${group.label}`}\n            points={polyPoints}\n            fill=\"none\"\n            stroke={group.color}\n            strokeWidth={3}\n            strokeLinejoin=\"round\"\n          />\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const size = window.ANYPLOT_SIZE;\n  const chartSize = size.height - HEADER_HEIGHT - FOOTER_HEIGHT;\n\n  return (\n    <div\n      style={{\n        width: size.width,\n        height: size.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: HEADER_HEIGHT,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          fontSize: 22,\n          fontWeight: 700,\n          color: t.ink,\n        }}\n      >\n        {TITLE}\n      </div>\n      <ChartsContainer\n        width={chartSize}\n        height={chartSize}\n        series={series}\n        xAxis={[{ scaleType: \"linear\", min: -domainLimit, max: domainLimit, position: \"none\" }]}\n        yAxis={[{ scaleType: \"linear\", min: -domainLimit, max: domainLimit, position: \"none\" }]}\n        margin={{\n          top: CHART_MARGIN,\n          bottom: CHART_MARGIN,\n          left: CHART_MARGIN,\n          right: CHART_MARGIN,\n        }}\n        skipAnimation\n      >\n        <PolarLayer />\n        <ScatterPlot />\n      </ChartsContainer>\n      <div\n        style={{\n          height: FOOTER_HEIGHT,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 36,\n        }}\n      >\n        {seriesGroups.map((group) => (\n          <div\n            key={`legend-${group.label}`}\n            style={{ display: \"flex\", alignItems: \"center\", gap: 10 }}\n          >\n            <span\n              style={{\n                width: 18,\n                height: 18,\n                borderRadius: \"50%\",\n                backgroundColor: group.color,\n                display: \"inline-block\",\n              }}\n            />\n            <span style={{ fontSize: 15, color: t.ink, fontWeight: 500 }}>{group.label}</span>\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n"}