{"spec_id":"map-marker-clustered","library":"muix","language":"javascript","code":"// anyplot.ai\n// map-marker-clustered: Clustered Marker Map\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 83/100 | Updated: 2026-10-23\n//# anyplot-orientation: square\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\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 { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst LAT_CELL = 0.55;\nconst LON_CELL = 0.75;\nconst EXTENT_PAD_DEG = 0.25; // degrees added around the data extent\n\n// Columns: set these to your data's column names\nconst LAT = \"Latitude (°)\"; // role: lat\nconst LON = \"Longitude (°)\"; // role: lon\nconst CATEGORY = \"Store format\"; // role: category\n\n// Data: replace this block with your own records, one object per row\nconst data = (() => {\n  let seed = 42;\n  const rng = () => {\n    seed = (1664525 * seed + 1013904223) >>> 0;\n    return seed / 4294967296;\n  };\n  const randomNormal = (mean: number, stdDev: number) => {\n    const u1 = Math.max(rng(), 1e-9);\n    const u2 = rng();\n    const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n    return mean + z * stdDev;\n  };\n\n  const sampleCategories = [\"Flagship\", \"Standard\", \"Kiosk\"];\n  const hubs = [\n    { lat: 47.6062, lon: -122.3321, count: 55, spread: 0.22, categoryBias: 0 }, // Seattle\n    { lat: 45.5152, lon: -122.6784, count: 42, spread: 0.2, categoryBias: 1 }, // Portland\n    { lat: 47.2529, lon: -122.4443, count: 26, spread: 0.16, categoryBias: 2 }, // Tacoma\n    { lat: 48.7519, lon: -122.4787, count: 18, spread: 0.14, categoryBias: 0 }, // Bellingham\n    { lat: 44.0582, lon: -123.0868, count: 16, spread: 0.14, categoryBias: 1 }, // Eugene\n  ];\n  const ruralStoreCount = 22;\n  const ruralLatRange = [43.7, 49.2];\n  const ruralLonRange = [-124.6, -119.8];\n\n  const rows: { [LAT]: number; [LON]: number; [CATEGORY]: string }[] = [];\n  hubs.forEach((hub) => {\n    for (let i = 0; i < hub.count; i++) {\n      const categoryIndex =\n        rng() < 0.65 ? hub.categoryBias : Math.floor(rng() * sampleCategories.length);\n      rows.push({\n        [LAT]: hub.lat + randomNormal(0, hub.spread),\n        [LON]: hub.lon + randomNormal(0, hub.spread * 1.3),\n        [CATEGORY]: sampleCategories[categoryIndex],\n      });\n    }\n  });\n  for (let i = 0; i < ruralStoreCount; i++) {\n    rows.push({\n      [LAT]: ruralLatRange[0] + rng() * (ruralLatRange[1] - ruralLatRange[0]),\n      [LON]: ruralLonRange[0] + rng() * (ruralLonRange[1] - ruralLonRange[0]),\n      [CATEGORY]: sampleCategories[Math.floor(rng() * sampleCategories.length)],\n    });\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst { width, height } = window.ANYPLOT_SIZE;\nconst MARGIN = { top: 24, right: 40, bottom: 20, left: 20 };\nconst X_AXIS_HEIGHT = 64;\nconst Y_AXIS_WIDTH = 76;\nconst TITLE_HEIGHT = 56;\nconst LEGEND_HEIGHT = 56;\n\n// Equal-distance framing: one degree of longitude is cos(latitude) of a degree of\n// latitude, so the data extent is fitted into the plot box at that ratio and the\n// looser dimension is widened around the data center to fill the box.\nconst allLats = data.map((d) => d[LAT]);\nconst allLons = data.map((d) => d[LON]);\nconst latMin = Math.min(...allLats) - EXTENT_PAD_DEG;\nconst latMax = Math.max(...allLats) + EXTENT_PAD_DEG;\nconst lonMin = Math.min(...allLons) - EXTENT_PAD_DEG;\nconst lonMax = Math.max(...allLons) + EXTENT_PAD_DEG;\nconst lonShrink = Math.cos((((latMin + latMax) / 2) * Math.PI) / 180);\nconst plotWidthPx = width - MARGIN.left - MARGIN.right - Y_AXIS_WIDTH;\nconst plotHeightPx =\n  height - TITLE_HEIGHT - LEGEND_HEIGHT - MARGIN.top - MARGIN.bottom - X_AXIS_HEIGHT;\nconst pxPerLat = Math.min(\n  plotHeightPx / (latMax - latMin),\n  plotWidthPx / ((lonMax - lonMin) * lonShrink),\n);\nconst latHalfSpan = plotHeightPx / pxPerLat / 2;\nconst lonHalfSpan = plotWidthPx / (pxPerLat * lonShrink) / 2;\nconst LAT_RANGE = [(latMin + latMax) / 2 - latHalfSpan, (latMin + latMax) / 2 + latHalfSpan];\nconst LON_RANGE = [(lonMin + lonMax) / 2 - lonHalfSpan, (lonMin + lonMax) / 2 + lonHalfSpan];\n\nconst categories = Array.from(new Set(data.map((d) => d[CATEGORY])));\nconst categoryColors = categories.map((_, i) => t.palette[i]);\n// Count text: dark or light ink, whichever contrasts more with the marker fill\nconst countInk = Object.fromEntries(\n  categories.map((cat, i) => {\n    const [r, g, b] = [1, 3, 5].map((k) => {\n      const c = parseInt(categoryColors[i].slice(k, k + 2), 16) / 255;\n      return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n    });\n    const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n    return [cat, luminance > 0.18 ? \"#1A1A17\" : \"#FAF8F1\"];\n  }),\n);\n\nconst cells = new Map<string, typeof data>();\ndata.forEach((store) => {\n  const key = `${Math.floor(store[LAT] / LAT_CELL)}_${Math.floor(store[LON] / LON_CELL)}`;\n  if (!cells.has(key)) cells.set(key, []);\n  cells.get(key)!.push(store);\n});\n\nconst clusters = Array.from(cells.values()).map((members, i) => {\n  const counts: Record<string, number> = {};\n  members.forEach((m) => {\n    counts[m[CATEGORY]] = (counts[m[CATEGORY]] || 0) + 1;\n  });\n  return {\n    id: `cluster-${i}`,\n    x: members.reduce((sum, m) => sum + m[LON], 0) / members.length,\n    y: members.reduce((sum, m) => sum + m[LAT], 0) / members.length,\n    z: categories.reduce((best, cat) => ((counts[cat] || 0) > (counts[best] || 0) ? cat : best)),\n    count: members.length,\n  };\n});\n\nconst individualStores = clusters.filter((c) => c.count === 1);\nconst smallClusters = clusters.filter((c) => c.count >= 2 && c.count <= 6);\nconst largeClusters = clusters.filter((c) => c.count > 6);\n\nconst TITLE = \"TrailBrew Coffee Co. · map-marker-clustered · javascript · muix · anyplot.ai\";\nconst TITLE_FONT_DEFAULT = 22;\nconst titleFontSize =\n  TITLE.length > 67 ? Math.round(TITLE_FONT_DEFAULT * (67 / TITLE.length)) : TITLE_FONT_DEFAULT;\n\nconst MARKER_SIZE = { single: 6, small: 17, large: 27 };\nconst SIZE_LEGEND = [\n  { label: \"1 store\", diameter: 2 * MARKER_SIZE.single },\n  { label: \"2–6 stores\", diameter: 2 * MARKER_SIZE.small },\n  { label: \"7+ stores\", diameter: 2 * MARKER_SIZE.large },\n];\n\nconst PACIFIC_COAST = [\n  [-124.2, 42.0],\n  [-124.15, 44.2],\n  [-124.35, 44.9],\n  [-124.4, 45.6],\n  [-124.0, 46.15],\n  [-124.35, 46.5],\n  [-124.4, 47.3],\n  [-124.45, 47.9],\n  [-124.7, 48.4],\n  [-124.7, 50.0],\n];\n\nconst PUGET_SOUND = [\n  [-123.3, 48.25],\n  [-122.9, 48.3],\n  [-122.6, 48.1],\n  [-122.4, 47.75],\n  [-122.35, 47.45],\n  [-122.5, 47.05],\n  [-122.65, 47.15],\n  [-122.55, 47.55],\n  [-122.65, 47.9],\n  [-122.95, 48.15],\n];\n\nconst CANADA_BORDER_LAT = 49.0;\nconst WA_OR_BORDER_LAT = 46.0;\n\nfunction GeographicBackdrop() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  if (!xScale || !yScale) return null;\n\n  // Clamp to the axis ranges so the water stays inside the plot area\n  const project = ([lon, lat]: number[]) =>\n    `${xScale(Math.max(lon, LON_RANGE[0]))},${yScale(Math.min(Math.max(lat, LAT_RANGE[0]), LAT_RANGE[1]))}`;\n  const oceanPoints = [[LON_RANGE[0], 42.0], ...PACIFIC_COAST, [LON_RANGE[0], 50.0]]\n    .map(project)\n    .join(\" \");\n  const soundPoints = PUGET_SOUND.map(project).join(\" \");\n  const border = { stroke: t.inkSoft, strokeWidth: 1.25, strokeDasharray: \"6 4\", opacity: 0.5 };\n\n  return (\n    <g pointerEvents=\"none\">\n      <polygon points={oceanPoints} fill={t.inkSoft} opacity={0.1} />\n      <polygon points={soundPoints} fill={t.inkSoft} opacity={0.1} />\n      <line\n        x1={xScale(-123.3)}\n        y1={yScale(CANADA_BORDER_LAT)}\n        x2={xScale(LON_RANGE[1])}\n        y2={yScale(CANADA_BORDER_LAT)}\n        {...border}\n      />\n      <line\n        x1={xScale(-124.0)}\n        y1={yScale(WA_OR_BORDER_LAT)}\n        x2={xScale(LON_RANGE[1])}\n        y2={yScale(WA_OR_BORDER_LAT)}\n        {...border}\n      />\n    </g>\n  );\n}\n\nfunction ClusterCountLabels() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  if (!xScale || !yScale) return null;\n\n  return (\n    <g pointerEvents=\"none\">\n      {[...smallClusters, ...largeClusters].map((c) => (\n        <text\n          key={c.id}\n          x={xScale(c.x)}\n          y={yScale(c.y)}\n          fontSize={c.count > 6 ? 16 : 13}\n          fontWeight={700}\n          fill={countInk[c.z]}\n          textAnchor=\"middle\"\n          dominantBaseline=\"central\"\n        >\n          {c.count}\n        </text>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <div style={{ width, height, backgroundColor: t.pageBg }}>\n      <div\n        style={{\n          height: TITLE_HEIGHT,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          fontSize: titleFontSize,\n          fontWeight: 600,\n          color: t.ink,\n        }}\n      >\n        {TITLE}\n      </div>\n      <ChartsContainer\n        width={width}\n        height={height - TITLE_HEIGHT - LEGEND_HEIGHT}\n        margin={MARGIN}\n        series={[\n          {\n            type: \"scatter\",\n            id: \"individual\",\n            data: individualStores,\n            label: \"Single location\",\n            markerSize: MARKER_SIZE.single,\n            zAxisId: \"category\",\n          },\n          {\n            type: \"scatter\",\n            id: \"small-cluster\",\n            data: smallClusters,\n            label: \"Small cluster (2–6 stores)\",\n            markerSize: MARKER_SIZE.small,\n            zAxisId: \"category\",\n          },\n          {\n            type: \"scatter\",\n            id: \"large-cluster\",\n            data: largeClusters,\n            label: \"Large cluster (7+ stores)\",\n            markerSize: MARKER_SIZE.large,\n            zAxisId: \"category\",\n          },\n        ]}\n        zAxis={[\n          {\n            id: \"category\",\n            colorMap: { type: \"ordinal\", values: categories, colors: categoryColors },\n          },\n        ]}\n        xAxis={[\n          {\n            scaleType: \"linear\",\n            min: LON_RANGE[0],\n            max: LON_RANGE[1],\n            tickMinStep: 1,\n            height: X_AXIS_HEIGHT,\n            label: LON,\n            valueFormatter: (v: number) => `${Math.abs(v).toFixed(0)}°${v < 0 ? \"W\" : \"E\"}`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: LAT_RANGE[0],\n            max: LAT_RANGE[1],\n            tickMinStep: 1,\n            width: Y_AXIS_WIDTH,\n            label: LAT,\n            valueFormatter: (v: number) => `${Math.abs(v).toFixed(0)}°${v < 0 ? \"S\" : \"N\"}`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      >\n        <GeographicBackdrop />\n        <ChartsGrid horizontal vertical />\n        <ScatterPlot skipAnimation />\n        <ClusterCountLabels />\n        <ChartsXAxis />\n        <ChartsYAxis />\n        <ChartsTooltip trigger=\"item\" />\n      </ChartsContainer>\n      <div\n        style={{\n          height: LEGEND_HEIGHT,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 36,\n        }}\n      >\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 16 }}>\n          <span style={{ fontSize: 14, color: t.inkSoft }}>{CATEGORY}:</span>\n          {categories.map((cat, i) => (\n            <div key={cat} style={{ display: \"flex\", alignItems: \"center\", gap: 6 }}>\n              <span\n                style={{\n                  width: 14,\n                  height: 14,\n                  borderRadius: \"50%\",\n                  backgroundColor: categoryColors[i],\n                  flexShrink: 0,\n                }}\n              />\n              <span style={{ fontSize: 14, color: t.ink }}>{cat}</span>\n            </div>\n          ))}\n        </div>\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 16 }}>\n          <span style={{ fontSize: 14, color: t.inkSoft }}>Cluster size:</span>\n          {SIZE_LEGEND.map((entry) => (\n            <div key={entry.label} style={{ display: \"flex\", alignItems: \"center\", gap: 6 }}>\n              <span\n                style={{\n                  width: entry.diameter,\n                  height: entry.diameter,\n                  borderRadius: \"50%\",\n                  backgroundColor: t.inkSoft,\n                  opacity: 0.55,\n                  flexShrink: 0,\n                }}\n              />\n              <span style={{ fontSize: 14, color: t.ink }}>{entry.label}</span>\n            </div>\n          ))}\n        </div>\n      </div>\n    </div>\n  );\n}\n"}