{"spec_id":"windrose-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// windrose-basic: Wind Rose Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\n//# anyplot-orientation: square\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\n// The 16-point compass, clockwise from north; each sector is centred on its point.\nconst COMPASS = [\"N\", \"NNE\", \"NE\", \"ENE\", \"E\", \"ESE\", \"SE\", \"SSE\", \"S\", \"SSW\", \"SW\", \"WSW\", \"W\", \"WNW\", \"NW\", \"NNW\"];\nconst SPEED_BINS = 4; // speed classes, few enough that neighbouring ramp steps stay apart; the last one is open-ended\nconst TOP_BIN_QUANTILE = 0.9; // the open-ended class starts near this quantile of the speeds\nconst RING_COUNT = 4; // about this many frequency rings\nconst NICE_STEPS = [1, 2, 2.5, 5, 10]; // round step multipliers for bin widths and rings\nconst SECTOR_GAP_DEG = 1.4; // gap between neighbouring spokes\nconst LABEL_BAND = 54; // px between the outer ring and the compass labels' edge\nconst TITLE = \"windrose-basic · javascript · muix · anyplot.ai\";\nconst TITLE_H = 80;\nconst LEGEND_H = 64;\n\n// Columns: set these to your data's column names\nconst DIRECTION = \"Wind direction (°)\"; // role: direction\nconst SPEED = \"Wind speed (m/s)\"; // role: speed\n\n// Data: replace this block with your own records, one object per row\n// Half a year of hourly readings at a coastal weather station: a prevailing\n// south-westerly, a brisk north-westerly regime and light winds from anywhere.\nconst data = (() => {\n  let a = 42;\n  const rand = () => {\n    a |= 0;\n    a = (a + 0x6d2b79f5) | 0;\n    let x = Math.imul(a ^ (a >>> 15), 1 | a);\n    x = (x + Math.imul(x ^ (x >>> 7), 61 | x)) ^ x;\n    return ((x ^ (x >>> 14)) >>> 0) / 4294967296;\n  };\n  const normal = () => Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-6))) * Math.cos(2 * Math.PI * rand());\n  return Array.from({ length: 4380 }, () => {\n    const regime = rand();\n    let direction;\n    let scale;\n    if (regime < 0.6) {\n      direction = 225 + normal() * 36;\n      scale = 3.4;\n    } else if (regime < 0.78) {\n      direction = 315 + normal() * 24;\n      scale = 3.0;\n    } else {\n      direction = rand() * 360;\n      scale = 1.7;\n    }\n    const speed = -Math.log(1 - rand()) * scale;\n    return {\n      [DIRECTION]: Math.round((((direction % 360) + 360) % 360) * 10) / 10,\n      [SPEED]: Math.round(speed * 100) / 100,\n    };\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => d[DIRECTION] != null && d[SPEED] != null);\nconst n = rows.length;\nconst SECTOR_DEG = 360 / COMPASS.length;\nconst SPEED_UNIT = SPEED.match(/\\(([^)]+)\\)\\s*$/)?.[1] ?? \"\";\n\n// Speed classes of one round width, chosen so the open-ended top class starts\n// near the TOP_BIN_QUANTILE of the observed speeds.\nconst sortedSpeeds = rows.map((d) => d[SPEED]).sort((x, y) => x - y);\nconst rawStep = sortedSpeeds[Math.floor(TOP_BIN_QUANTILE * (n - 1))] / (SPEED_BINS - 1);\nconst stepMagnitude = 10 ** Math.floor(Math.log10(rawStep));\nconst speedStep = NICE_STEPS.map((m) => m * stepMagnitude).find((s) => s >= rawStep);\nconst binStarts = Array.from({ length: SPEED_BINS }, (_, i) => i * speedStep);\nconst binLabels = binStarts.map((lo, i) =>\n  i < SPEED_BINS - 1 ? `${lo}–${lo + speedStep} ${SPEED_UNIT}` : `≥ ${lo} ${SPEED_UNIT}`,\n);\n\n// Share of all observations (%) per compass sector and speed class\nconst counts = COMPASS.map(() => binStarts.map(() => 0));\nrows.forEach((d) => {\n  const sector = Math.round((((d[DIRECTION] % 360) + 360) % 360) / SECTOR_DEG) % COMPASS.length;\n  const bin = Math.min(SPEED_BINS - 1, Math.floor(d[SPEED] / speedStep));\n  counts[sector][bin] += 1;\n});\nconst pct = counts.map((row) => row.map((c) => (c / n) * 100));\nconst cumulative = pct.map((row) => row.map((_, i) => row.slice(0, i + 1).reduce((x, y) => x + y, 0)));\nconst totals = cumulative.map((row) => row[row.length - 1]);\nconst maxTotal = Math.max(...totals);\nconst rawRing = maxTotal / RING_COUNT;\nconst ringMagnitude = 10 ** Math.floor(Math.log10(rawRing));\nconst ringStep = NICE_STEPS.map((m) => m * ringMagnitude).find((s) => s >= rawRing);\nconst ringMax = ringStep * Math.ceil(maxTotal / ringStep);\nconst rings = Array.from({ length: Math.round(ringMax / ringStep) }, (_, i) => (i + 1) * ringStep);\n\n// Calm to strong along the Imprint sequential ramp\nconst seqRgb = t.seq.map((hex) => [1, 3, 5].map((k) => parseInt(hex.slice(k, k + 2), 16)));\nconst binColors = binStarts.map(\n  (_, i) =>\n    `rgb(${seqRgb[0].map((c, k) => Math.round(c + ((seqRgb[1][k] - c) * i) / (SPEED_BINS - 1))).join(\",\")})`,\n);\n\n// Wedges in unit radii (share of the outer ring) and SVG angles (0 at 3 o'clock)\nconst toSvg = Math.PI / 180;\nconst wedges = COMPASS.flatMap((_, s) =>\n  binStarts.map((_, b) => ({\n    key: `${s}-${b}`,\n    color: binColors[b],\n    inner: (cumulative[s][b] - pct[s][b]) / ringMax,\n    outer: cumulative[s][b] / ringMax,\n    a0: ((s - 0.5) * SECTOR_DEG + SECTOR_GAP_DEG / 2 - 90) * toSvg,\n    a1: ((s + 0.5) * SECTOR_DEG - SECTOR_GAP_DEG / 2 - 90) * toSvg,\n  })),\n).filter((w) => w.outer > w.inner);\n// Ring labels run along the sector boundary whose two neighbours hold the fewest observations\nconst quietBoundary = COMPASS.reduce(\n  (best, _, s) => (totals[s] + totals[(s + 1) % COMPASS.length] < totals[best] + totals[(best + 1) % COMPASS.length] ? s : best),\n  0,\n);\nconst ringAngle = ((quietBoundary + 0.5) * SECTOR_DEG - 90) * toSvg;\nconst SUBTITLE = `${n.toLocaleString(\"en-US\")} observations · ${COMPASS.length} sectors of ${SECTOR_DEG}° · spoke length: share of all observations (%)`;\n\n// The community package has no polar bar chart: a custom layer maps the stacked\n// sectors onto the chart's drawing area.\nfunction WindRoseLayer() {\n  const { left, top, width, height } = useDrawingArea();\n  const cx = left + width / 2;\n  const cy = top + height / 2;\n  const R = Math.min(width, height) / 2 - LABEL_BAND;\n\n  return (\n    <g>\n      {rings.map((level) => (\n        <circle key={`ring-${level}`} cx={cx} cy={cy} r={(level / ringMax) * R} fill=\"none\" stroke={t.grid} strokeWidth={1.25} />\n      ))}\n      {wedges.map((w) => (\n        <path\n          key={w.key}\n          d={`M ${cx + w.outer * R * Math.cos(w.a0)} ${cy + w.outer * R * Math.sin(w.a0)} A ${w.outer * R} ${w.outer * R} 0 0 1 ${cx + w.outer * R * Math.cos(w.a1)} ${cy + w.outer * R * Math.sin(w.a1)} L ${cx + w.inner * R * Math.cos(w.a1)} ${cy + w.inner * R * Math.sin(w.a1)} A ${w.inner * R} ${w.inner * R} 0 0 0 ${cx + w.inner * R * Math.cos(w.a0)} ${cy + w.inner * R * Math.sin(w.a0)} Z`}\n          fill={w.color}\n          stroke={t.pageBg}\n          strokeWidth={1}\n        />\n      ))}\n      {rings.map((level) => (\n        <text\n          key={`ring-label-${level}`}\n          x={cx + (level / ringMax) * R * Math.cos(ringAngle)}\n          y={cy + (level / ringMax) * R * Math.sin(ringAngle)}\n          dx={4}\n          dy={-4}\n          fontSize={18}\n          fill={t.inkSoft}\n          stroke={t.pageBg}\n          strokeWidth={4}\n          paintOrder=\"stroke\"\n        >\n          {`${level} %`}\n        </text>\n      ))}\n      {COMPASS.map((point, s) => {\n        const a = (s * SECTOR_DEG - 90) * toSvg;\n        const cos = Math.cos(a);\n        const sin = Math.sin(a);\n        const rank = s % 4 === 0 ? 0 : s % 2 === 0 ? 1 : 2; // cardinal, intercardinal, secondary\n        return (\n          <text\n            key={`label-${point}`}\n            x={cx + (R + 14) * cos}\n            y={cy + (R + 14) * sin}\n            textAnchor={cos > 0.15 ? \"start\" : cos < -0.15 ? \"end\" : \"middle\"}\n            dominantBaseline={sin > 0.5 ? \"hanging\" : sin < -0.5 ? \"auto\" : \"central\"}\n            fontSize={[20, 19, 18][rank]}\n            fontWeight={[700, 600, 400][rank]}\n            fill={rank < 2 ? t.ink : t.inkSoft}\n          >\n            {point}\n          </text>\n        );\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, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: TITLE_H, paddingTop: 18, boxSizing: \"border-box\", textAlign: \"center\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.2, marginTop: 8 }}>{SUBTITLE}</div>\n      </div>\n      <ChartsContainer\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        series={[]}\n        skipAnimation\n        margin={{ top: 16, right: 24, bottom: 8, left: 24 }}\n      >\n        <WindRoseLayer />\n      </ChartsContainer>\n      <div\n        style={{\n          height: LEGEND_H,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 26,\n        }}\n      >\n        <span style={{ fontSize: 16, fontWeight: 600, color: t.ink }}>{SPEED}</span>\n        {binLabels.map((label, i) => (\n          <div key={label} style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <span style={{ width: 18, height: 18, borderRadius: 3, background: binColors[i], display: \"inline-block\" }} />\n            <span style={{ fontSize: 16, color: t.ink }}>{label}</span>\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n"}