{"spec_id":"hexbin-map-geographic","library":"muix","language":"javascript","code":"// anyplot.ai\n// hexbin-map-geographic: Hexagonal Binning Map\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 86/100 | Updated: 2026-11-08\n//# anyplot-orientation: square\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\nimport { ContinuousColorLegend, continuousColorLegendClasses } from \"@mui/x-charts/ChartsLegend\";\nimport { useDrawingArea, useXScale, useYScale, useZColorScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst HEX_RADIUS_SHARE = 0.032; // hexagon radius as a share of the projected map width\nconst AGGREGATION: \"count\" | \"sum\" | \"mean\" = \"count\"; // statistic per cell; sum and mean read the VALUE column\nconst PAD_SHARE = 0.06; // map padding around the points, as a share of their extent\nconst HEX_OPACITY = 0.62; // translucent cells let the base map show through\nconst KM_PER_DEG_LAT = 111.2; // length of one degree of latitude\n\n// Columns: set these to your data's column names\nconst LON = \"Longitude\"; // role: lon\nconst LAT = \"Latitude\"; // role: lat\nconst VALUE = \"Group size\"; // role: value (animals per sighting, optional for count)\n\n// Data: replace this block with your own records, one object per point\n// Synthetic gray-whale and common-dolphin sighting reports off Southern\n// California: clusters offshore of three whale-watching launch points (Santa\n// Barbara Channel, Dana Point, La Jolla) plus sparse sightings up and down the\n// coast, every report at least 15 km from the mainland shore and 4 km from the\n// islands.\n// Base map geometry: approximate real coastline vertices, north to south, the\n// land polygon east of it, and the larger offshore islands.\nconst COASTLINE = [\n  [-120.64, 35.14], // Pismo Beach\n  [-120.64, 34.9], // Point Sal\n  [-120.65, 34.58], // Point Arguello\n  [-120.47, 34.45], // Point Conception\n  [-119.84, 34.41], // Santa Barbara\n  [-119.3, 34.28], // Ventura\n  [-119.1, 34.09], // Point Mugu\n  [-118.8, 34.03], // Malibu\n  [-118.5, 33.99], // Santa Monica\n  [-118.41, 33.74], // Palos Verdes\n  [-118.19, 33.75], // Long Beach\n  [-117.93, 33.6], // Newport Beach\n  [-117.7, 33.46], // Dana Point\n  [-117.38, 33.2], // Oceanside\n  [-117.27, 32.85], // La Jolla\n  [-117.17, 32.72], // San Diego Bay\n  [-117.13, 32.55], // Point Loma\n  [-117.12, 32.53], // Tijuana\n  [-117.06, 32.35], // Rosarito\n  [-116.62, 31.87], // Ensenada\n];\nconst LAND = [...COASTLINE, [-114.0, 31.87], [-114.0, 35.14]];\nconst ISLANDS = [\n  // San Miguel\n  [[-120.45, 34.04], [-120.36, 34.08], [-120.31, 34.04], [-120.36, 34.01], [-120.43, 34.02]],\n  // Santa Rosa\n  [[-120.24, 34.0], [-120.12, 34.03], [-119.98, 33.98], [-120.04, 33.9], [-120.17, 33.92]],\n  // Santa Cruz\n  [[-119.92, 34.07], [-119.75, 34.06], [-119.54, 34.04], [-119.55, 33.99], [-119.72, 33.96], [-119.88, 33.99]],\n  // Anacapa\n  [[-119.44, 34.02], [-119.36, 34.02], [-119.36, 34.0], [-119.44, 34.0]],\n  // San Nicolas\n  [[-119.58, 33.27], [-119.45, 33.25], [-119.42, 33.22], [-119.55, 33.21]],\n  // Santa Catalina\n  [[-118.61, 33.48], [-118.5, 33.44], [-118.31, 33.33], [-118.33, 33.3], [-118.46, 33.34], [-118.6, 33.43]],\n  // San Clemente\n  [[-118.6, 33.03], [-118.54, 33.02], [-118.35, 32.82], [-118.42, 32.81]],\n];\n\nconst data = (() => {\n  let seed = 42;\n  const rand = () => {\n    seed |= 0;\n    seed = (seed + 0x6d2b79f5) | 0;\n    let x = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n    x = (x + Math.imul(x ^ (x >>> 7), 61 | x)) ^ x;\n    return ((x ^ (x >>> 14)) >>> 0) / 4294967296;\n  };\n  const gaussian = () => Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n  const minShoreKm = 15; // no report closer to the mainland shore than this\n  const minIslandKm = 4; // nor closer to an island shore than this\n  const cosRef = Math.cos((33.5 * Math.PI) / 180);\n  // Distance from a point to a closed polygon outline in km; -1 for a point inside it\n  const islandKm = (lon: number, lat: number, ring: number[][]) => {\n    let inside = false;\n    let nearest = Infinity;\n    for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {\n      const [lonA, latA] = ring[j];\n      const [lonB, latB] = ring[i];\n      if (latA > lat !== latB > lat && lon < lonA + ((lat - latA) / (latB - latA)) * (lonB - lonA)) inside = !inside;\n      const dx = (lonB - lonA) * cosRef;\n      const dy = latB - latA;\n      const u = Math.min(1, Math.max(0, ((lon - lonA) * cosRef * dx + (lat - latA) * dy) / (dx * dx + dy * dy)));\n      nearest = Math.min(nearest, Math.hypot((lon - lonA) * cosRef - u * dx, lat - latA - u * dy));\n    }\n    return inside ? -1 : nearest * KM_PER_DEG_LAT;\n  };\n  const clearOfIslands = (lon: number, lat: number) => ISLANDS.every((ring) => islandKm(lon, lat, ring) >= minIslandKm);\n  const groupSize = () => Math.max(1, Math.round(Math.exp(0.9 + 0.7 * gaussian())));\n  // Distance from a point at sea to the mainland coastline in km; -1 for a point on land\n  const offshoreKm = (lon: number, lat: number) => {\n    let coastLon = -Infinity;\n    for (let i = 0; i < COASTLINE.length - 1; i += 1) {\n      const [lonA, latA] = COASTLINE[i];\n      const [lonB, latB] = COASTLINE[i + 1];\n      if ((lat - latA) * (lat - latB) <= 0) {\n        coastLon = lonA + ((lat - latA) / (latB - latA)) * (lonB - lonA);\n        break;\n      }\n    }\n    if (lon >= coastLon) return -1;\n    let nearest = Infinity;\n    for (let i = 0; i < COASTLINE.length - 1; i += 1) {\n      const ax = COASTLINE[i][0] * cosRef;\n      const ay = COASTLINE[i][1];\n      const dx = COASTLINE[i + 1][0] * cosRef - ax;\n      const dy = COASTLINE[i + 1][1] - ay;\n      const u = Math.min(1, Math.max(0, ((lon * cosRef - ax) * dx + (lat - ay) * dy) / (dx * dx + dy * dy)));\n      nearest = Math.min(nearest, Math.hypot(lon * cosRef - ax - u * dx, lat - ay - u * dy));\n    }\n    return nearest * KM_PER_DEG_LAT;\n  };\n  const inView = (lon: number, lat: number) => lon > -120.6 && lon < -117.05 && lat > 32.45 && lat < 34.55;\n\n  const hotspots = [\n    { lon: -119.72, lat: 34.16, sdLon: 0.3, sdLat: 0.09, n: 520 }, // Santa Barbara Channel\n    { lon: -117.9, lat: 33.3, sdLon: 0.13, sdLat: 0.1, n: 380 }, // off Dana Point\n    { lon: -117.47, lat: 32.8, sdLon: 0.1, sdLat: 0.1, n: 340 }, // off La Jolla\n  ];\n  const rows: { [LON]: number; [LAT]: number; [VALUE]: number }[] = [];\n  for (const spot of hotspots) {\n    let kept = 0;\n    while (kept < spot.n) {\n      const lon = spot.lon + gaussian() * spot.sdLon;\n      const lat = spot.lat + gaussian() * spot.sdLat;\n      if (inView(lon, lat) && offshoreKm(lon, lat) >= minShoreKm && clearOfIslands(lon, lat)) {\n        rows.push({ [LON]: Number(lon.toFixed(4)), [LAT]: Number(lat.toFixed(4)), [VALUE]: groupSize() });\n        kept += 1;\n      }\n    }\n  }\n  let sparse = 0;\n  while (sparse < 280) {\n    const lon = -120.6 + rand() * 3.55;\n    const lat = 32.45 + rand() * 2.1;\n    const km = offshoreKm(lon, lat);\n    if (km >= minShoreKm && km <= minShoreKm + 40 && clearOfIslands(lon, lat)) {\n      rows.push({ [LON]: Number(lon.toFixed(4)), [LAT]: Number(lat.toFixed(4)), [VALUE]: groupSize() });\n      sparse += 1;\n    }\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst { width: W, height: H } = window.ANYPLOT_SIZE;\nconst HEADER_H = 84;\nconst LEGEND_H = 76;\nconst MARGIN = { top: 16, right: 32, bottom: 12, left: 20 };\nconst X_AXIS_H = 60;\nconst Y_AXIS_W = 84;\nconst DRAW_W = W - MARGIN.left - MARGIN.right - Y_AXIS_W;\nconst DRAW_H = H - HEADER_H - LEGEND_H - MARGIN.top - MARGIN.bottom - X_AXIS_H;\n\n// Equirectangular projection scaled at the mid latitude: one projected unit is\n// one degree of latitude, so px per degree of latitude = px per degree of\n// longitude / cos(mid latitude).\nconst lons = data.map((d) => d[LON]);\nconst lats = data.map((d) => d[LAT]);\nconst lonLo = Math.min(...lons);\nconst lonHi = Math.max(...lons);\nconst latLo = Math.min(...lats);\nconst latHi = Math.max(...lats);\nconst lonMid = (lonLo + lonHi) / 2;\nconst latMid = (latLo + latHi) / 2;\nconst cosLat = Math.cos((latMid * Math.PI) / 180);\n// Padded extent in projected units, the shorter side widened to the drawing area's aspect\nconst paddedX = (lonHi - lonLo) * cosLat * (1 + 2 * PAD_SHARE);\nconst paddedY = (latHi - latLo) * (1 + 2 * PAD_SHARE);\nconst spanX = Math.max(paddedX, paddedY * (DRAW_W / DRAW_H));\nconst spanY = spanX / (DRAW_W / DRAW_H);\nconst xMin = lonMid - spanX / cosLat / 2;\nconst xMax = lonMid + spanX / cosLat / 2;\nconst yMin = latMid - spanY / 2;\nconst yMax = latMid + spanY / 2;\n\n// Flat-top hexagonal binning in projected units (axial coordinates, cube rounding)\nconst R = spanX * HEX_RADIUS_SHARE;\nconst binCounts = new Map<string, { q: number; r: number; count: number; sum: number }>();\nfor (const d of data) {\n  const px = d[LON] * cosLat;\n  const py = d[LAT];\n  const qf = ((2 / 3) * px) / R;\n  const rf = ((-1 / 3) * px + (Math.sqrt(3) / 3) * py) / R;\n  const sf = -qf - rf;\n  let q = Math.round(qf);\n  let r = Math.round(rf);\n  const s = Math.round(sf);\n  const dq = Math.abs(q - qf);\n  const dr = Math.abs(r - rf);\n  const ds = Math.abs(s - sf);\n  if (dq > dr && dq > ds) q = -r - s;\n  else if (dr > ds) r = -q - s;\n  const key = `${q},${r}`;\n  const bin = binCounts.get(key) ?? { q, r, count: 0, sum: 0 };\n  bin.count += 1;\n  bin.sum += d[VALUE] ?? 0;\n  binCounts.set(key, bin);\n}\nconst bins = [...binCounts.entries()].map(([key, { q, r, count, sum }]) => ({\n  id: key,\n  lon: (R * 1.5 * q) / cosLat,\n  lat: R * Math.sqrt(3) * (r + q / 2),\n  count,\n  sum,\n  mean: sum / count,\n  stat: { count, sum, mean: sum / count }[AGGREGATION],\n}));\nconst statMin = Math.min(...bins.map((b) => b.stat));\nconst statMax = Math.max(...bins.map((b) => b.stat));\n// Hexagon corners as offsets in degrees of longitude and latitude\nconst HEX_CORNERS = Array.from({ length: 6 }, (_, k) => [(R * Math.cos((k * Math.PI) / 3)) / cosLat, R * Math.sin((k * Math.PI) / 3)]);\n\nconst STAT_LABEL = {\n  count: \"Sightings per hex cell (count)\",\n  sum: `${VALUE} per hex cell (sum)`,\n  mean: `${VALUE} per hex cell (mean)`,\n}[AGGREGATION];\nconst formatStat = (v: number) => (AGGREGATION === \"mean\" ? v.toFixed(1) : String(Math.round(v)));\nconst CLIP_ID = \"hexbin-map-clip\";\nconst formatLon = (v: number) => `${Math.abs(v).toFixed(1)}°${v < 0 ? \"W\" : \"E\"}`;\nconst formatLat = (v: number) => `${Math.abs(v).toFixed(1)}°${v < 0 ? \"S\" : \"N\"}`;\nconst TITLE = \"Gray Whale & Dolphin Sightings · hexbin-map-geographic · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${data.length.toLocaleString(\"en-US\")} points binned into ${bins.length} hexagons of ${(R * KM_PER_DEG_LAT).toFixed(0)} km radius · equirectangular map scaled at ${formatLat(latMid)}`;\n\n// Base map in data coordinates: land tint and coastline, clipped to the drawing area\nfunction BaseMap() {\n  const xScale = useXScale() as (v: number) => number;\n  const yScale = useYScale() as (v: number) => number;\n  const { left, top, width, height } = useDrawingArea();\n  return (\n    <g>\n      <defs>\n        <clipPath id={CLIP_ID}>\n          <rect x={left} y={top} width={width} height={height} />\n        </clipPath>\n      </defs>\n      <g clipPath={`url(#${CLIP_ID})`}>\n        <polygon points={LAND.map(([lon, lat]) => `${xScale(lon)},${yScale(lat)}`).join(\" \")} fill={t.grid} />\n        <polyline\n          points={COASTLINE.map(([lon, lat]) => `${xScale(lon)},${yScale(lat)}`).join(\" \")}\n          fill=\"none\"\n          stroke={t.inkSoft}\n          strokeWidth={1.5}\n        />\n        {ISLANDS.map((ring, i) => (\n          <polygon\n            key={i}\n            points={ring.map(([lon, lat]) => `${xScale(lon)},${yScale(lat)}`).join(\" \")}\n            fill={t.grid}\n            stroke={t.inkSoft}\n            strokeWidth={1.5}\n          />\n        ))}\n      </g>\n    </g>\n  );\n}\n\n// Hexagons in data coordinates, coloured by the z axis colour map\nfunction HexCells() {\n  const xScale = useXScale() as (v: number) => number;\n  const yScale = useYScale() as (v: number) => number;\n  const colorScale = useZColorScale() as (v: number) => string;\n  return (\n    <g clipPath={`url(#${CLIP_ID})`}>\n      {bins.map((b) => (\n        <polygon\n          key={b.id}\n          points={HEX_CORNERS.map(([dx, dy]) => `${xScale(b.lon + dx)},${yScale(b.lat + dy)}`).join(\" \")}\n          fill={colorScale(b.stat)}\n          fillOpacity={HEX_OPACITY}\n          stroke={t.pageBg}\n          strokeWidth={1.5}\n        />\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <Box sx={{ width: W, height: H, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\", overflow: \"hidden\" }}>\n      <Box sx={{ height: HEADER_H, pt: \"16px\", px: \"20px\", textAlign: \"center\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 21, fontWeight: 600, color: t.ink, lineHeight: 1.3 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.6 }}>{SUBTITLE}</Typography>\n      </Box>\n      <ChartsDataProvider\n        width={W}\n        height={H - HEADER_H - LEGEND_H}\n        skipAnimation\n        margin={MARGIN}\n        // The cell centres as a scatter series: hover shows each cell's statistics\n        series={[\n          {\n            type: \"scatter\",\n            id: \"hex-cells\",\n            label: STAT_LABEL,\n            data: bins.map((b) => ({ id: b.id, x: b.lon, y: b.lat })),\n            valueFormatter: (_v, { dataIndex }) => {\n              const b = bins[dataIndex];\n              return `count ${b.count} · sum ${b.sum} · mean ${b.mean.toFixed(1)} · ${formatLat(b.lat)}, ${formatLon(b.lon)}`;\n            },\n          },\n        ]}\n        xAxis={[\n          {\n            scaleType: \"linear\",\n            min: xMin,\n            max: xMax,\n            height: X_AXIS_H,\n            label: LON,\n            tickLabelMinGap: 24,\n            valueFormatter: formatLon,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: yMin,\n            max: yMax,\n            width: Y_AXIS_W,\n            label: LAT,\n            valueFormatter: formatLat,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        zAxis={[{ colorMap: { type: \"continuous\", min: statMin, max: statMax, color: [t.seq[0], t.seq[1]] } }]}\n      >\n        <ChartsWrapper\n          legendPosition={{ vertical: \"bottom\", horizontal: \"center\" }}\n          legendDirection=\"horizontal\"\n          sx={{ width: W, height: H - HEADER_H }}\n        >\n          <Box\n            sx={{\n              gridArea: \"legend\",\n              height: LEGEND_H,\n              width: W * 0.45,\n              display: \"flex\",\n              flexDirection: \"column\",\n              alignItems: \"stretch\",\n              pt: \"6px\",\n              boxSizing: \"border-box\",\n            }}\n          >\n            <Typography sx={{ color: t.ink, fontSize: 15, textAlign: \"center\", mb: \"4px\" }}>{STAT_LABEL}</Typography>\n            <ContinuousColorLegend\n              direction=\"horizontal\"\n              thickness={16}\n              labelPosition=\"end\"\n              minLabel={({ value }) => formatStat(Number(value))}\n              maxLabel={({ value }) => formatStat(Number(value))}\n              // Same opacity as the cells, so the bar shows the colours as drawn\n              sx={{ color: t.inkSoft, fontSize: 14, [`& .${continuousColorLegendClasses.gradient}`]: { opacity: HEX_OPACITY } }}\n            />\n          </Box>\n          <ChartsSurface>\n            <ChartsGrid vertical horizontal sx={{ \"& line\": { stroke: t.grid } }} />\n            <BaseMap />\n            <HexCells />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n          <ChartsTooltip trigger=\"item\" />\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </Box>\n  );\n}\n"}