{"spec_id":"contour-filled","library":"muix","language":"javascript","code":"// anyplot.ai\n// contour-filled: Filled Contour Plot\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-24\n\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\nconst SIZE = window.ANYPLOT_SIZE;\n\n// Constants\nconst TITLE = \"contour-filled · javascript · muix · anyplot.ai\";\nconst FONT = \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif\";\nconst NUM_BANDS = 10;\n\n// Columns: set these to your data's column names\nconst X = \"Zonal offset (°)\"; // role: x\nconst Y = \"Meridional offset (°)\"; // role: y\nconst Z = \"Temperature anomaly (°C)\"; // role: z\n\n// Data: replace this block with your own records\nconst data = (() => {\n  const sampleGrid = 90;\n  const sampleSpan = 6;\n  const rows: Record<string, number>[] = [];\n  for (let j = 0; j < sampleGrid; j += 1) {\n    const y = -sampleSpan / 2 + (j / (sampleGrid - 1)) * sampleSpan;\n    for (let i = 0; i < sampleGrid; i += 1) {\n      const x = -sampleSpan / 2 + (i / (sampleGrid - 1)) * sampleSpan;\n      const warm = 2.0 * Math.exp(-((x - 1.3) * (x - 1.3) + (y - 0.9) * (y - 0.9)) * 0.55);\n      const cool = -1.6 * Math.exp(-((x + 1.4) * (x + 1.4) + (y + 1.0) * (y + 1.0)) * 0.65);\n      rows.push({ [X]: x, [Y]: y, [Z]: warm + cool });\n    }\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst xs = Array.from(new Set(data.map((d) => Number(d[X])))).sort((a, b) => a - b);\nconst ys = Array.from(new Set(data.map((d) => Number(d[Y])))).sort((a, b) => a - b);\nconst nX = xs.length;\nconst nY = ys.length;\nconst xMin = xs[0];\nconst xMax = xs[nX - 1];\nconst yMin = ys[0];\nconst yMax = ys[nY - 1];\n\nconst zGrid = Array.from({ length: nY }, () => new Array(nX).fill(NaN));\nconst xIndex = new Map(xs.map((v, i) => [v, i]));\nconst yIndex = new Map(ys.map((v, j) => [v, j]));\nfor (const row of data) {\n  const val = Number(row[Z]);\n  if (Number.isFinite(val)) {\n    zGrid[yIndex.get(Number(row[Y]))!][xIndex.get(Number(row[X]))!] = val;\n  }\n}\n\nconst validZ = data.map((d) => Number(d[Z])).filter((v) => Number.isFinite(v));\nconst zMin = Math.min(...validZ);\nconst zMax = Math.max(...validZ);\nconst vAbs = Math.max(Math.abs(zMin), Math.abs(zMax));\nconst SUBTITLE = `${Z} across ${nX}×${nY} grid · ${NUM_BANDS} filled contour bands`;\n\nconst divStops = [t.div[2], t.div[1], t.div[0]].map((hex) => {\n  const n = parseInt(hex.slice(1), 16);\n  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];\n});\n\nconst levels = Array.from({ length: NUM_BANDS }, (_, k) => -vAbs + (k * 2 * vAbs) / NUM_BANDS);\nconst levelEdges = Array.from(\n  { length: NUM_BANDS + 1 },\n  (_, k) => -vAbs + (k * 2 * vAbs) / NUM_BANDS,\n);\n\nconst bandColors = Array.from({ length: NUM_BANDS }, (_, k) => {\n  const pos = k / (NUM_BANDS - 1);\n  const [start, end, ratio] =\n    pos < 0.5\n      ? [divStops[0], divStops[1], pos / 0.5]\n      : [divStops[1], divStops[2], (pos - 0.5) / 0.5];\n  const r = Math.round(start[0] + (end[0] - start[0]) * ratio);\n  const g = Math.round(start[1] + (end[1] - start[1]) * ratio);\n  const b = Math.round(start[2] + (end[2] - start[2]) * ratio);\n  return `rgb(${r}, ${g}, ${b})`;\n});\n\nconst triangles: { x: number; y: number; z: number }[][] = [];\nfor (let j = 0; j < nY - 1; j += 1) {\n  for (let i = 0; i < nX - 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 center = {\n      x: (sw.x + se.x) / 2,\n      y: (sw.y + nw.y) / 2,\n      z: (sw.z + se.z + ne.z + nw.z) / 4,\n    };\n    triangles.push([sw, se, center], [se, ne, center], [ne, nw, center], [nw, sw, center]);\n  }\n}\n\nconst validTriangles = triangles.filter(\n  ([a, b, c]) => !Number.isNaN(a.z) && !Number.isNaN(b.z) && !Number.isNaN(c.z),\n);\n\nconst bandGeometry: { x: number; y: number }[][][] = [];\nconst isolineGeometry: { x: number; y: number }[][][] = [];\nfor (let k = 1; k < NUM_BANDS; k += 1) {\n  const threshold = levels[k];\n  const polys: { x: number; y: number }[][] = [];\n  const segments: { x: number; y: number }[][] = [];\n  for (const [a, b, c] of validTriangles) {\n    const inA = a.z >= threshold;\n    const inB = b.z >= threshold;\n    const inC = c.z >= threshold;\n    const nIn = (inA ? 1 : 0) + (inB ? 1 : 0) + (inC ? 1 : 0);\n    if (nIn === 0) continue;\n    if (nIn === 3) {\n      polys.push([a, b, c]);\n      continue;\n    }\n    const rAB = b.z !== a.z ? (threshold - a.z) / (b.z - a.z) : 0.5;\n    const ab = { x: a.x + rAB * (b.x - a.x), y: a.y + rAB * (b.y - a.y) };\n    const rBC = c.z !== b.z ? (threshold - b.z) / (c.z - b.z) : 0.5;\n    const bc = { x: b.x + rBC * (c.x - b.x), y: b.y + rBC * (c.y - b.y) };\n    const rCA = a.z !== c.z ? (threshold - c.z) / (a.z - c.z) : 0.5;\n    const ca = { x: c.x + rCA * (a.x - c.x), y: c.y + rCA * (a.y - c.y) };\n\n    if (nIn === 1) {\n      if (inA) {\n        polys.push([a, ab, ca]);\n        segments.push([ab, ca]);\n      } else if (inB) {\n        polys.push([b, bc, ab]);\n        segments.push([bc, ab]);\n      } else {\n        polys.push([c, ca, bc]);\n        segments.push([ca, bc]);\n      }\n    } else if (!inC) {\n      polys.push([a, b, bc, ca]);\n      segments.push([ca, bc]);\n    } else if (!inA) {\n      polys.push([b, c, ca, ab]);\n      segments.push([ab, ca]);\n    } else {\n      polys.push([c, a, ab, bc]);\n      segments.push([bc, ab]);\n    }\n  }\n  bandGeometry.push(polys);\n  isolineGeometry.push(segments);\n}\n\nfunction FilledContourLayer() {\n  const xScale = useXScale(\"x\") as any;\n  const yScale = useYScale(\"y\") as any;\n  const { left, top, width, height } = useDrawingArea();\n\n  const basePath = validTriangles\n    .map(\n      (tri) =>\n        tri\n          .map((p, k) => `${k === 0 ? \"M\" : \"L\"} ${xScale(p.x).toFixed(1)},${yScale(p.y).toFixed(1)}`)\n          .join(\" \") + \" Z\",\n    )\n    .join(\" \");\n\n  const barX = left + width + 36;\n  const barW = 22;\n  const barH = height * 0.78;\n  const barTop = top + (height - barH) / 2;\n  const stepH = barH / NUM_BANDS;\n\n  return (\n    <g fontFamily={FONT}>\n      <path d={basePath} fill={bandColors[0]} stroke={bandColors[0]} strokeWidth={0.75} />\n      {bandGeometry.map((polys, idx) => {\n        const dPath = polys\n          .map(\n            (poly) =>\n              poly\n                .map((p, k) => {\n                  const px = xScale(p.x).toFixed(1);\n                  const py = yScale(p.y).toFixed(1);\n                  return `${k === 0 ? \"M\" : \"L\"} ${px},${py}`;\n                })\n                .join(\" \") + \" Z\",\n          )\n          .join(\" \");\n        return (\n          <path\n            key={`band-${idx}`}\n            d={dPath}\n            fill={bandColors[idx + 1]}\n            stroke={bandColors[idx + 1]}\n            strokeWidth={0.75}\n          />\n        );\n      })}\n      {isolineGeometry.map((segments, idx) => {\n        const dPath = segments\n          .map(([p0, p1]) => {\n            const x0 = xScale(p0.x).toFixed(1);\n            const y0 = yScale(p0.y).toFixed(1);\n            const x1 = xScale(p1.x).toFixed(1);\n            const y1 = yScale(p1.y).toFixed(1);\n            return `M ${x0},${y0} L ${x1},${y1}`;\n          })\n          .join(\" \");\n        return (\n          <path\n            key={`iso-${idx}`}\n            d={dPath}\n            stroke={t.ink}\n            strokeOpacity={0.28}\n            strokeWidth={1}\n            fill=\"none\"\n          />\n        );\n      })}\n\n      {/* Discrete contour-band colorbar */}\n      {bandColors.map((col, k) => {\n        const y = barTop + (NUM_BANDS - 1 - k) * stepH;\n        return (\n          <rect\n            key={`cb-${k}`}\n            x={barX}\n            y={y}\n            width={barW}\n            height={stepH + 0.5}\n            fill={col}\n          />\n        );\n      })}\n      <rect\n        x={barX}\n        y={barTop}\n        width={barW}\n        height={barH}\n        fill=\"none\"\n        stroke={t.inkSoft}\n        strokeWidth={1.2}\n      />\n      {levelEdges.map((val, k) => {\n        if (k % 2 !== 0) return null;\n        const y = barTop + (NUM_BANDS - k) * stepH;\n        return (\n          <g key={`cbt-${k}`}>\n            <line\n              x1={barX + barW}\n              y1={y}\n              x2={barX + barW + 6}\n              y2={y}\n              stroke={t.inkSoft}\n              strokeWidth={1.2}\n            />\n            <text\n              x={barX + barW + 10}\n              y={y}\n              dominantBaseline=\"central\"\n              fontSize={14}\n              fill={t.inkSoft}\n            >\n              {val >= 0 ? `+${val.toFixed(1)}` : val.toFixed(1)}\n            </text>\n          </g>\n        );\n      })}\n      <text\n        x={barX + barW + 68}\n        y={barTop + barH / 2}\n        textAnchor=\"middle\"\n        dominantBaseline=\"central\"\n        fontSize={15}\n        fontWeight={500}\n        fill={t.ink}\n        transform={`rotate(-90, ${barX + barW + 68}, ${barTop + barH / 2})`}\n      >\n        {Z}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const chartW = SIZE.width - 48;\n  const chartH = SIZE.height - 110;\n\n  return (\n    <Box\n      sx={{\n        width: SIZE.width,\n        height: SIZE.height,\n        bgcolor: t.pageBg,\n        color: t.ink,\n        fontFamily: FONT,\n        display: \"flex\",\n        flexDirection: \"column\",\n        alignItems: \"center\",\n        pt: \"18px\",\n        px: \"24px\",\n        boxSizing: \"border-box\",\n      }}\n    >\n      <Typography\n        sx={{\n          fontSize: 22,\n          fontWeight: 700,\n          color: t.ink,\n          fontFamily: FONT,\n          textAlign: \"center\",\n          lineHeight: 1.2,\n        }}\n      >\n        {TITLE}\n      </Typography>\n      <Typography\n        sx={{\n          fontSize: 15,\n          color: t.inkSoft,\n          fontFamily: FONT,\n          textAlign: \"center\",\n          mt: \"4px\",\n          mb: \"4px\",\n        }}\n      >\n        {SUBTITLE}\n      </Typography>\n\n      <ChartsContainer\n        width={chartW}\n        height={chartH}\n        series={[]}\n        margin={{ top: 20, right: 160, bottom: 20, left: 20 }}\n        skipAnimation\n        xAxis={[\n          {\n            id: \"x\",\n            scaleType: \"linear\",\n            min: xMin,\n            max: xMax,\n            height: 60,\n            tickNumber: 13,\n            label: X,\n            labelStyle: { fontSize: 15, fill: t.ink, fontFamily: FONT },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontFamily: FONT },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"y\",\n            scaleType: \"linear\",\n            min: yMin,\n            max: yMax,\n            width: 84,\n            tickNumber: 13,\n            label: Y,\n            labelStyle: { fontSize: 15, fill: t.ink, fontFamily: FONT },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontFamily: FONT },\n          },\n        ]}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n        }}\n      >\n        <FilledContourLayer />\n        <ChartsXAxis axisId=\"x\" />\n        <ChartsYAxis axisId=\"y\" />\n      </ChartsContainer>\n    </Box>\n  );\n}\n"}