{"spec_id":"contour-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// contour-basic: Basic Contour Plot\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/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 { PiecewiseColorLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useXScale, useYScale, useZColorScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst LEVEL_COUNT = 9; // filled bands between the field's minimum and maximum, evenly stepped\nconst ISOLINE_INK = \"#1A1A17\"; // fixed ink: the bands keep their colours in both themes\n\n// Columns: set these to your data's column names\nconst EASTING = \"Easting (km)\"; // role: x\nconst NORTHING = \"Northing (km)\"; // role: y\nconst ELEVATION = \"Elevation (km)\"; // role: z\n\n// Data: replace this block with your own records, one object per grid point\n// Terrain of a 6 × 6 km survey square: two summits joined by a low diagonal ridge, sampled on a 100 × 100 grid\nconst data = (() => {\n  const gridSize = 100;\n  const halfSpan = 3;\n  const rows: Record<string, number>[] = [];\n  for (let j = 0; j < gridSize; j += 1) {\n    const y = -halfSpan + (2 * halfSpan * j) / (gridSize - 1);\n    for (let i = 0; i < gridSize; i += 1) {\n      const x = -halfSpan + (2 * halfSpan * i) / (gridSize - 1);\n      const northSummit = Math.exp(-((x - 1) ** 2 + (y - 0.5) ** 2) * 1.5);\n      const southSummit = 0.75 * Math.exp(-((x + 1) ** 2 + (y + 1) ** 2) * 2.0);\n      const ridge = 0.175 * Math.exp(-((x - y) ** 2) * 0.8);\n      rows.push({ [EASTING]: x, [NORTHING]: y, [ELEVATION]: northSummit + southSummit + ridge });\n    }\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\n// Regular grid rebuilt from the records: sorted coordinates, z indexed as zGrid[row][column]\nconst xs = [...new Set(data.map((d) => d[EASTING]))].sort((a, b) => a - b);\nconst ys = [...new Set(data.map((d) => d[NORTHING]))].sort((a, b) => a - b);\nconst xIndex = new Map(xs.map((v, i) => [v, i]));\nconst yIndex = new Map(ys.map((v, j) => [v, j]));\nconst zGrid = ys.map(() => xs.map(() => NaN));\ndata.forEach((d) => {\n  zGrid[yIndex.get(d[NORTHING])!][xIndex.get(d[EASTING])!] = d[ELEVATION];\n});\nconst zValues = data.map((d) => d[ELEVATION]).filter((v) => Number.isFinite(v));\nconst zMin = Math.min(...zValues);\nconst zMax = Math.max(...zValues);\nconst levelStep = (zMax - zMin) / LEVEL_COUNT;\nconst levels = Array.from({ length: LEVEL_COUNT }, (_, k) => zMin + k * levelStep);\nconst thresholds = levels.slice(1);\n\n// Sequential Imprint ramp t.seq[0] -> t.seq[1], one step per band\nconst [seqLow, seqHigh] = t.seq.map((hex: string) => [16, 8, 0].map((shift) => (parseInt(hex.slice(1), 16) >> shift) & 255));\nconst bandColors = levels.map(\n  (_, k) => `rgb(${seqLow.map((c: number, ch: number) => Math.round(c + ((seqHigh[ch] - c) * k) / (LEVEL_COUNT - 1))).join(\", \")})`,\n);\n\n// Marching triangles: each grid cell splits into four triangles around its centre, which resolves\n// saddles; per level, the part of every triangle at or above the level and the cut along the level\ntype Pt = { x: number; y: number; z: number };\nconst triangles: Pt[][] = [];\nfor (let j = 0; j < ys.length - 1; j += 1) {\n  for (let i = 0; i < xs.length - 1; i += 1) {\n    const sw = { x: xs[i], y: ys[j], z: zGrid[j][i] };\n    const se = { x: xs[i + 1], y: ys[j], z: zGrid[j][i + 1] };\n    const ne = { x: xs[i + 1], y: ys[j + 1], z: zGrid[j + 1][i + 1] };\n    const nw = { x: xs[i], y: ys[j + 1], z: zGrid[j + 1][i] };\n    const centre = { x: (sw.x + se.x) / 2, y: (sw.y + nw.y) / 2, z: (sw.z + se.z + ne.z + nw.z) / 4 };\n    [[sw, se], [se, ne], [ne, nw], [nw, sw]].forEach(([a, b]) => {\n      if ([a.z, b.z, centre.z].every((z) => Number.isFinite(z))) triangles.push([a, b, centre]);\n    });\n  }\n}\nconst bandPolygons: { x: number; y: number }[][][] = [];\nconst isolines: { x: number; y: number }[][][] = [];\nlevels.forEach((level) => {\n  const polys: { x: number; y: number }[][] = [];\n  const cuts: { x: number; y: number }[][] = [];\n  triangles.forEach((tri) => {\n    const inside = tri.map((p) => p.z >= level);\n    const count = inside.filter(Boolean).length;\n    if (count === 0) return;\n    if (count === 3) {\n      polys.push(tri);\n      return;\n    }\n    // Walk the three edges; keep inside vertices and the level crossing on every edge that changes side\n    const ring: { x: number; y: number }[] = [];\n    const cut: { x: number; y: number }[] = [];\n    tri.forEach((p, k) => {\n      const q = tri[(k + 1) % 3];\n      if (inside[k]) ring.push(p);\n      if (inside[k] !== inside[(k + 1) % 3]) {\n        const r = (level - p.z) / (q.z - p.z);\n        const crossing = { x: p.x + r * (q.x - p.x), y: p.y + r * (q.y - p.y) };\n        ring.push(crossing);\n        cut.push(crossing);\n      }\n    });\n    polys.push(ring);\n    cuts.push(cut);\n  });\n  bandPolygons.push(polys);\n  isolines.push(cuts);\n});\n\n// Layout: equal px per km on both axes, the map centred with its colour bar beside it\nconst { width: W, height: H } = window.ANYPLOT_SIZE;\nconst HEADER_H = 84;\nconst X_AXIS_H = 60;\nconst Y_AXIS_W = 72;\nconst MARGIN = { top: 16, bottom: 20, left: 24, right: 28 };\nconst LEGEND_W = 140;\nconst xSpan = xs[xs.length - 1] - xs[0];\nconst ySpan = ys[ys.length - 1] - ys[0];\nconst plotH = Math.min(H - HEADER_H - X_AXIS_H - MARGIN.top - MARGIN.bottom, ((W - LEGEND_W - Y_AXIS_W - MARGIN.left - MARGIN.right) * ySpan) / xSpan);\nconst plotW = (plotH * xSpan) / ySpan;\nconst surfaceW = MARGIN.left + Y_AXIS_W + plotW + MARGIN.right;\nconst surfaceH = MARGIN.top + plotH + X_AXIS_H + MARGIN.bottom;\n\nconst TITLE = \"Survey Terrain · contour-basic · javascript · muix · anyplot.ai\";\nconst subtitle = `${xs.length} × ${ys.length} grid points · ${LEVEL_COUNT} levels evenly stepped by ${levelStep.toFixed(2)}`;\n\nfunction ContourLayer() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  // Band fills come from the zAxis piecewise colorMap, the same scale the colour bar reads\n  const colorScale = useZColorScale()!;\n  const toPath = (shapes: { x: number; y: number }[][], close: boolean) =>\n    shapes\n      .map((shape) => shape.map((p, k) => `${k === 0 ? \"M\" : \"L\"}${xScale(p.x)!.toFixed(1)},${yScale(p.y)!.toFixed(1)}`).join(\"\") + (close ? \"Z\" : \"\"))\n      .join(\"\");\n  return (\n    <g>\n      {bandPolygons.map((polys, k) => {\n        const fill = String(colorScale(levels[k] + levelStep / 2));\n        return <path key={`band-${k}`} d={toPath(polys, true)} fill={fill} stroke={fill} strokeWidth={0.75} />;\n      })}\n      {isolines.map((cuts, k) => (\n        <path key={`iso-${k}`} d={toPath(cuts, false)} fill=\"none\" stroke={ISOLINE_INK} strokeOpacity={0.6} strokeWidth={1.5} />\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\", alignItems: \"center\" }}>\n      <Box sx={{ height: HEADER_H, display: \"flex\", flexDirection: \"column\", justifyContent: \"center\", alignItems: \"center\", gap: \"6px\", pt: \"8px\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.2 }}>{subtitle}</Typography>\n      </Box>\n      {/* The spare height below the header is split evenly above and below the map */}\n      <Box sx={{ flex: 1, display: \"flex\", alignItems: \"center\", justifyContent: \"center\" }}>\n        <ChartsDataProvider\n          width={surfaceW}\n          height={surfaceH}\n          series={[]}\n          skipAnimation\n          margin={MARGIN}\n          xAxis={[\n            {\n              id: \"x\",\n              scaleType: \"linear\",\n              min: xs[0],\n              max: xs[xs.length - 1],\n              label: EASTING,\n              height: X_AXIS_H,\n              labelStyle: { fontSize: 16, fill: t.ink },\n              tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            },\n          ]}\n          yAxis={[\n            {\n              id: \"y\",\n              scaleType: \"linear\",\n              min: ys[0],\n              max: ys[ys.length - 1],\n              label: NORTHING,\n              width: Y_AXIS_W,\n              labelStyle: { fontSize: 16, fill: t.ink },\n              tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            },\n          ]}\n          zAxis={[{ id: \"z\", colorMap: { type: \"piecewise\", thresholds, colors: bandColors } }]}\n        >\n          <ChartsWrapper\n            legendPosition={{ vertical: \"middle\", horizontal: \"end\" }}\n            legendDirection=\"vertical\"\n            sx={{ width: surfaceW + LEGEND_W, height: surfaceH }}\n          >\n            <Box sx={{ gridArea: \"legend\", width: LEGEND_W, display: \"flex\", flexDirection: \"column\", alignItems: \"flex-start\", gap: \"10px\" }}>\n              <Typography sx={{ fontSize: 16, fontWeight: 500, color: t.ink }}>{ELEVATION}</Typography>\n              <PiecewiseColorLegend\n                axisDirection=\"z\"\n                axisId=\"z\"\n                direction=\"vertical\"\n                labelPosition=\"inline-end\"\n                markType=\"square\"\n                labelFormatter={({ min, max }) => `${Number(min ?? zMin).toFixed(2)} – ${Number(max ?? zMax).toFixed(2)}`}\n                sx={{ fontSize: 14, color: t.inkSoft, gap: \"6px\" }}\n              />\n            </Box>\n            <ChartsSurface\n              sx={{\n                \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n                \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n              }}\n            >\n              <ContourLayer />\n              <ChartsXAxis axisId=\"x\" />\n              <ChartsYAxis axisId=\"y\" />\n            </ChartsSurface>\n          </ChartsWrapper>\n        </ChartsDataProvider>\n      </Box>\n    </Box>\n  );\n}\n"}