{"spec_id":"hexbin-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// hexbin-basic: Basic Hexbin Plot\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 85/100 | Updated: 2026-10-23\n//# anyplot-orientation: square\n\nimport { ScatterChart } from \"@mui/x-charts/ScatterChart\";\nimport { ContinuousColorLegend } from \"@mui/x-charts/ChartsLegend\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst HEX_RADIUS_SHARE = 0.075; // hexagon radius as a share of the plotted half-width\n\n// Columns: set these to your data's column names\nconst X = \"Distance east of plaza (m)\"; // role: x\nconst Y = \"Distance north of plaza (m)\"; // role: y\n\n// Data: replace this block with your own records, one object per row\n// Pedestrian GPS pings across a city district (three foot-traffic hotspots plus\n// an ambient background cluster).\nconst data = (() => {\n  function makeLcg(seed: number) {\n    let state = seed >>> 0;\n    return () => {\n      state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n      return state / 4294967296;\n    };\n  }\n  const rng = makeLcg(42);\n\n  function gaussian() {\n    const u1 = Math.max(rng(), 1e-9);\n    const u2 = rng();\n    return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n  }\n\n  const domainLimit = 60;\n  const clusters = [\n    { cx: 0, cy: 6, sx: 9, sy: 8, weight: 0.42 }, // Central Plaza\n    { cx: 34, cy: -24, sx: 7, sy: 10, weight: 0.28 }, // Transit Hub\n    { cx: -31, cy: 21, sx: 11, sy: 6, weight: 0.22 }, // Waterfront Promenade\n    { cx: 0, cy: 0, sx: 30, sy: 26, weight: 0.08 }, // Ambient foot traffic\n  ];\n\n  const pointCount = 30000;\n  const rows: { [X]: number; [Y]: number }[] = [];\n  let attempts = 0;\n  while (rows.length < pointCount && attempts < pointCount * 4) {\n    attempts += 1;\n    const r = rng();\n    let acc = 0;\n    let cluster = clusters[clusters.length - 1];\n    for (let c = 0; c < clusters.length; c += 1) {\n      acc += clusters[c].weight;\n      if (r <= acc) {\n        cluster = clusters[c];\n        break;\n      }\n    }\n    const x = cluster.cx + gaussian() * cluster.sx;\n    const y = cluster.cy + gaussian() * cluster.sy;\n    if (Math.abs(x) > domainLimit || Math.abs(y) > domainLimit) continue;\n    rows.push({ [X]: x, [Y]: y });\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst DOMAIN = Math.ceil(\n  Math.max(...data.map((d) => Math.max(Math.abs(d[X]), Math.abs(d[Y])))),\n);\nconst HEX_RADIUS = DOMAIN * HEX_RADIUS_SHARE;\nconst hexDx = HEX_RADIUS * Math.sqrt(3);\nconst hexDy = HEX_RADIUS * 1.5;\n\n// Hexagonal binning: count the points per pointy-top hex cell (id \"col-row\")\nconst countsById = new Map<string, number>();\ndata.forEach((row) => {\n  const py1 = row[Y] / hexDy;\n  let pj = Math.round(py1);\n  const px1 = row[X] / hexDx - (pj & 1) / 2;\n  let pi = Math.round(px1);\n  const py2 = py1 - pj;\n  if (Math.abs(py2) * 3 > 1) {\n    const px2 = px1 - pi;\n    const pi2 = pi + (px1 < pi ? -1 : 1) / 2;\n    const pj2 = pj + (py1 < pj ? -1 : 1);\n    const px3 = px1 - pi2;\n    const py3 = py2 - pj2;\n    if (px2 * px2 + py2 * py2 > px3 * px3 + py3 * py3) {\n      pi = pi2 + (pj & 1 ? 1 : -1) / 2;\n      pj = pj2;\n    }\n  }\n  const id = `${pi}-${pj}`;\n  countsById.set(id, (countsById.get(id) ?? 0) + 1);\n});\nconst binCountMax = Math.max(...countsById.values());\nconst binCountMin = Math.min(...countsById.values());\n\n// Full hex grid over the domain, so empty cells show in a faint tint\nconst hexBinPoints: { id: string; x: number; y: number; z: number; isEmpty: boolean }[] = [];\nfor (let pj = Math.floor(-DOMAIN / hexDy) - 1; pj <= Math.ceil(DOMAIN / hexDy) + 1; pj += 1) {\n  const offset = (pj & 1) / 2;\n  for (let pi = Math.floor(-DOMAIN / hexDx - offset) - 1; pi <= Math.ceil(DOMAIN / hexDx - offset) + 1; pi += 1) {\n    const cx = (pi + offset) * hexDx;\n    const cy = pj * hexDy;\n    if (Math.abs(cx) > DOMAIN + HEX_RADIUS || Math.abs(cy) > DOMAIN + HEX_RADIUS) continue;\n    const count = countsById.get(`${pi}-${pj}`) ?? 0;\n    hexBinPoints.push({ id: `${pi}-${pj}`, x: cx, y: cy, z: count || binCountMin, isEmpty: count === 0 });\n  }\n}\n\n// Color on a log scale so both dense cores and sparse fringes remain distinct.\nconst colorDomainMin = Math.log1p(binCountMin);\nconst colorDomainMax = Math.log1p(binCountMax);\nconst seqStart = parseInt(t.seq[0].slice(1), 16);\nconst seqEnd = parseInt(t.seq[1].slice(1), 16);\n\nfunction logSequentialColor(ratio: number) {\n  const count = binCountMin + ratio * (binCountMax - binCountMin);\n  const logRatio = Math.min(\n    1,\n    Math.max(0, (Math.log1p(count) - colorDomainMin) / (colorDomainMax - colorDomainMin || 1)),\n  );\n  return `#${[16, 8, 0]\n    .map((shift) => {\n      const a = (seqStart >> shift) & 255;\n      const b = (seqEnd >> shift) & 255;\n      return Math.round(a + (b - a) * logRatio).toString(16).padStart(2, \"0\");\n    })\n    .join(\"\")}`;\n}\n\nfunction HexCell(props: any) {\n  const { series, xScale, yScale, colorGetter, color } = props;\n  const radiusX = Math.abs(xScale(HEX_RADIUS) - xScale(0));\n  const radiusY = Math.abs(yScale(HEX_RADIUS) - yScale(0));\n\n  const [xr0, xr1] = xScale.range();\n  const [yr0, yr1] = yScale.range();\n  const clipX = Math.min(xr0, xr1);\n  const clipY = Math.min(yr0, yr1);\n  const clipWidth = Math.abs(xr1 - xr0);\n  const clipHeight = Math.abs(yr1 - yr0);\n\n  return (\n    <g clipPath=\"url(#hexbin-plot-clip)\">\n      <defs>\n        <clipPath id=\"hexbin-plot-clip\">\n          <rect x={clipX} y={clipY} width={clipWidth} height={clipHeight} />\n        </clipPath>\n      </defs>\n      {series.data.map((point: any, i: number) => {\n        const ccx = xScale(point.x);\n        const ccy = yScale(point.y);\n        let d = \"\";\n        for (let k = 0; k < 6; k += 1) {\n          const angle = (k * Math.PI) / 3;\n          const vx = ccx + Math.sin(angle) * radiusX;\n          const vy = ccy - Math.cos(angle) * radiusY;\n          d += `${k === 0 ? \"M\" : \"L\"}${vx},${vy}`;\n        }\n        return (\n          <path\n            key={point.id}\n            d={`${d}Z`}\n            fill={point.isEmpty ? t.seq[0] : colorGetter ? colorGetter(i) : color}\n            fillOpacity={point.isEmpty ? 0.12 : 1}\n            stroke={t.pageBg}\n            strokeWidth={1}\n          />\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const titleHeight = 70;\n  const captionHeight = 56;\n\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <Typography\n        sx={{\n          color: t.ink,\n          fontSize: 26,\n          fontWeight: 600,\n          textAlign: \"center\",\n          lineHeight: 1.2,\n          pt: \"18px\",\n          height: titleHeight,\n          fontFamily: \"inherit\",\n        }}\n      >\n        hexbin-basic · javascript · muix · anyplot.ai\n      </Typography>\n      <ScatterChart\n        width={width}\n        height={height - titleHeight - captionHeight}\n        skipAnimation\n        disableHitArea\n        series={[\n          {\n            id: \"hex-density\",\n            type: \"scatter\",\n            data: hexBinPoints,\n            label: \"Ping count\",\n            zAxisId: \"count\",\n          },\n        ]}\n        xAxis={[\n          {\n            height: 68,\n            scaleType: \"linear\",\n            min: -DOMAIN,\n            max: DOMAIN,\n            label: X,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            width: 88,\n            scaleType: \"linear\",\n            min: -DOMAIN,\n            max: DOMAIN,\n            label: Y,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        zAxis={[\n          {\n            id: \"count\",\n            min: binCountMin,\n            max: binCountMax,\n            colorMap: {\n              type: \"continuous\",\n              min: binCountMin,\n              max: binCountMax,\n              color: logSequentialColor,\n            },\n          },\n        ]}\n        // right margin sized so the plot area is square: equal px per metre keeps hexagons regular\n        margin={{ top: 30, right: 80, bottom: 24, left: 80 }}\n        slots={{ scatter: HexCell, legend: ContinuousColorLegend }}\n        slotProps={{\n          legend: {\n            axisId: \"count\",\n            axisDirection: \"z\",\n            direction: \"horizontal\",\n            position: { vertical: \"bottom\", horizontal: \"center\" },\n            thickness: 16,\n            sx: {\n              width: \"45%\",\n              color: t.inkSoft,\n              fontSize: 14,\n              fontFamily: \"inherit\",\n            },\n          } as any,\n        }}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n        }}\n      />\n      <Typography\n        sx={{\n          height: captionHeight,\n          pt: \"6px\",\n          textAlign: \"center\",\n          color: t.inkSoft,\n          fontSize: 14,\n          fontFamily: \"inherit\",\n        }}\n      >\n        Ping count per bin (log scale)\n      </Typography>\n    </Box>\n  );\n}\n"}