{"spec_id":"contour-basic","library":"chartjs","language":"javascript","code":"// anyplot.ai\n// contour-basic: Basic Contour Plot\n// Library: chartjs 4.6.1 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n\n//# anyplot-orientation: square\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TARGET_LEVELS = 14; // about this many evenly stepped isolines across the field's range\nconst REFINE = 4; // interpolated steps per grid cell, so isolines and band edges curve between grid nodes\n\n// Columns: set these to your data's column names\nconst X = \"Easting (km)\"; // role: x\nconst Y = \"Northing (km)\"; // role: y\nconst Z = \"Elevation anomaly (m)\"; // role: z\n\n// Data: replace this block with your own records, one object per grid point\n// Terrain elevation anomaly over a 6 km x 6 km survey area, modeled by the \"peaks\" surface on a 70 x 70 grid\nconst N = 70;\nconst RANGE = 3;\nconst data = [];\nfor (let i = 0; i < N; i++) {\n  for (let j = 0; j < N; j++) {\n    const x = -RANGE + (2 * RANGE * i) / (N - 1);\n    const y = -RANGE + (2 * RANGE * j) / (N - 1);\n    const z =\n      3 * (1 - x) ** 2 * Math.exp(-(x ** 2) - (y + 1) ** 2) -\n      10 * (x / 5 - x ** 3 - y ** 5) * Math.exp(-(x ** 2) - y ** 2) -\n      (1 / 3) * Math.exp(-((x + 1) ** 2) - y ** 2);\n    data.push({ [X]: x, [Y]: y, [Z]: z });\n  }\n}\n\n// Plot: reads only data and the constants above\n// Pivot the records into a grid: grid[i][j] is z at (xs[i], ys[j])\nconst xs = [...new Set(data.map((d) => d[X]))].sort((a, b) => a - b);\nconst ys = [...new Set(data.map((d) => d[Y]))].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 grid = xs.map(() => ys.map(() => NaN));\nfor (const d of data) grid[xIndex.get(d[X])][yIndex.get(d[Y])] = d[Z];\nconst zFinite = data.map((d) => d[Z]).filter(Number.isFinite);\nconst zMin = zFinite.reduce((a, b) => Math.min(a, b));\nconst zMax = zFinite.reduce((a, b) => Math.max(a, b));\n\n// Catmull-Rom refinement along x, then along y (linear phantom nodes at the ends); each pass refines the\n// columns of the current matrix and stores them as rows, so two passes return fine[i][j] on the refined grid\nlet fine = grid;\nfor (let pass = 0; pass < 2; pass++) {\n  fine = fine[0].map((_, j) => {\n    const line = fine.map((row) => row[j]);\n    const n = line.length;\n    const at = (k) => (k < 0 ? 2 * line[0] - line[1] : k >= n ? 2 * line[n - 1] - line[n - 2] : line[k]);\n    const out = [];\n    for (let k = 0; k < n - 1; k++) {\n      const [p0, p1, p2, p3] = [at(k - 1), at(k), at(k + 1), at(k + 2)];\n      for (let s = 0; s < REFINE; s++) {\n        const u = s / REFINE;\n        out.push(p1 + 0.5 * u * (p2 - p0 + u * (2 * p0 - 5 * p1 + 4 * p2 - p3 + u * (3 * (p1 - p2) + p3 - p0))));\n      }\n    }\n    out.push(line[n - 1]);\n    return out;\n  });\n}\n// The refined nodes sit at even steps between neighbouring grid coordinates\nconst [fineXs, fineYs] = [xs, ys].map((coords) =>\n  coords.flatMap((v, k) =>\n    k < coords.length - 1 ? Array.from({ length: REFINE }, (_, s) => v + (s / REFINE) * (coords[k + 1] - v)) : [v],\n  ),\n);\n\n// Evenly stepped levels at a round step (1, 2, 2.5 or 5 times a power of ten)\nconst rawStep = (zMax - zMin) / TARGET_LEVELS;\nconst magnitude = 10 ** Math.floor(Math.log10(rawStep));\nconst step = [1, 2, 2.5, 5, 10]\n  .map((m) => m * magnitude)\n  .reduce((best, s) => (Math.abs(s - rawStep) < Math.abs(best - rawStep) ? s : best));\nconst levels = [];\nfor (let k = Math.ceil(zMin / step); k * step <= zMax; k++) levels.push(Number((k * step).toFixed(10)));\n\n// Imprint colormap: imprint_div centered on zero for a two-signed field, imprint_seq otherwise\nconst hexToRgb = (hex) => [1, 3, 5].map((o) => parseInt(hex.slice(o, o + 2), 16));\nconst mix = (a, b, f) => a.map((v, c) => Math.round(v + (b[c] - v) * Math.max(0, Math.min(1, f))));\nconst [divLow, divMid, divHigh] = t.div.map(hexToRgb);\nconst [seqLow, seqHigh] = t.seq.map(hexToRgb);\nconst colorAt = (z) =>\n  zMin < 0 && zMax > 0\n    ? z < 0\n      ? mix(divMid, divLow, z / zMin)\n      : mix(divMid, divHigh, z / zMax)\n    : mix(seqLow, seqHigh, (z - zMin) / (zMax - zMin));\n// Band k lies between levels[k - 1] and levels[k]; band 0 sits below the lowest level\nconst bandOf = (z) => Math.min(levels.length, Math.max(0, Math.floor((z - levels[0]) / step) + 1));\nconst bandRgb = Array.from({ length: levels.length + 1 }, (_, k) =>\n  colorAt(Math.min(zMax, Math.max(zMin, levels[0] + (k - 0.5) * step))),\n);\n\n// Isolines by marching squares on the refined grid; a saddle cell is resolved by its center value\nconst [inkR, inkG, inkB] = hexToRgb(t.ink);\nconst datasets = levels.map((level) => {\n  const points = [];\n  for (let i = 0; i < fineXs.length - 1; i++) {\n    for (let j = 0; j < fineYs.length - 1; j++) {\n      const corners = [\n        [i, j],\n        [i + 1, j],\n        [i + 1, j + 1],\n        [i, j + 1],\n      ];\n      const zs = corners.map(([a, b]) => fine[a][b]);\n      const above = zs.map((z) => z >= level);\n      if (!zs.every(Number.isFinite) || above.every((v) => v === above[0])) continue;\n      const crossings = [];\n      for (let e = 0; e < 4; e++) {\n        const f = (e + 1) % 4;\n        if (above[e] === above[f]) continue;\n        const s = (level - zs[e]) / (zs[f] - zs[e]);\n        const [[ia, ja], [ib, jb]] = [corners[e], corners[f]];\n        crossings.push({\n          x: fineXs[ia] + s * (fineXs[ib] - fineXs[ia]),\n          y: fineYs[ja] + s * (fineYs[jb] - fineYs[ja]),\n        });\n      }\n      const centerAbove = zs.reduce((a, b) => a + b) / 4 >= level;\n      const pairs =\n        crossings.length === 2 ? [[0, 1]] : centerAbove === above[0] ? [[0, 1], [2, 3]] : [[3, 0], [1, 2]];\n      for (const [a, b] of pairs) points.push(crossings[a], crossings[b], { x: null, y: null });\n    }\n  }\n  return {\n    label: String(level),\n    data: points,\n    showLine: true,\n    // A tension routes the path through Chart.js's bezier drawing, which keeps sub-pixel positions; the default\n    // straight-line path merges points per whole pixel column and steps steep isolines. Two-point segments stay straight.\n    tension: 0.5,\n    borderColor: `rgba(${inkR},${inkG},${inkB},0.5)`,\n    borderWidth: 1.25,\n    borderCapStyle: \"round\",\n    pointRadius: 0,\n    pointHoverRadius: 0,\n    pointHitRadius: 6,\n  };\n});\n\n// Filled bands: each device pixel of the plot area takes the band of the bilinearly sampled refined field\nlet bandImage = null;\nconst bandFillPlugin = {\n  id: \"bandFill\",\n  beforeDatasetsDraw(chart) {\n    const { ctx, chartArea: ca, scales } = chart;\n    const dpr = chart.currentDevicePixelRatio;\n    const w = Math.round((ca.right - ca.left) * dpr);\n    const h = Math.round((ca.bottom - ca.top) * dpr);\n    if (!bandImage || bandImage.width !== w || bandImage.height !== h) {\n      bandImage = ctx.createImageData(w, h);\n      // Fractional refined-grid index of every pixel column and row (-1 outside the grid), by binary search\n      const [cols, rows] = [\n        [fineXs, w, scales.x, ca.left],\n        [fineYs, h, scales.y, ca.top],\n      ].map(([coords, count, scale, start]) =>\n        Array.from({ length: count }, (_, k) => {\n          const v = scale.getValueForPixel(start + (k + 0.5) / dpr);\n          if (!(v >= coords[0] && v <= coords[coords.length - 1])) return -1;\n          let lo = 0;\n          let hi = coords.length - 1;\n          while (hi - lo > 1) {\n            const mid = (lo + hi) >> 1;\n            if (coords[mid] <= v) lo = mid;\n            else hi = mid;\n          }\n          return lo + (v - coords[lo]) / (coords[hi] - coords[lo]);\n        }),\n      );\n      for (let r = 0; r < h; r++) {\n        if (rows[r] < 0) continue;\n        const j = Math.min(Math.floor(rows[r]), fineYs.length - 2);\n        const b = rows[r] - j;\n        for (let c = 0; c < w; c++) {\n          if (cols[c] < 0) continue;\n          const i = Math.min(Math.floor(cols[c]), fineXs.length - 2);\n          const a = cols[c] - i;\n          const z =\n            (1 - a) * (1 - b) * fine[i][j] + a * (1 - b) * fine[i + 1][j] + (1 - a) * b * fine[i][j + 1] + a * b * fine[i + 1][j + 1];\n          if (!Number.isFinite(z)) continue;\n          const o = (r * w + c) * 4;\n          bandImage.data.set(bandRgb[bandOf(z)], o);\n          bandImage.data[o + 3] = 255;\n        }\n      }\n    }\n    ctx.putImageData(bandImage, Math.round(ca.left * dpr), Math.round(ca.top * dpr));\n  },\n};\n\n// Color bar: the same bands as the plot, a tick at every isoline level, the quantity as its title\nconst colorBarPlugin = {\n  id: \"colorBar\",\n  afterDraw(chart) {\n    const { ctx, chartArea: ca } = chart;\n    const barX = ca.right + 28;\n    const barW = 26;\n    const toY = (z) => ca.bottom - ((z - zMin) / (zMax - zMin)) * (ca.bottom - ca.top);\n    const edges = [zMin, ...levels, zMax];\n    ctx.save();\n    for (let k = 0; k < edges.length - 1; k++) {\n      ctx.fillStyle = `rgb(${bandRgb[k].join(\",\")})`;\n      ctx.fillRect(barX, toY(edges[k + 1]), barW, toY(edges[k]) - toY(edges[k + 1]));\n    }\n    ctx.strokeStyle = t.inkSoft;\n    ctx.lineWidth = 1;\n    ctx.strokeRect(barX, ca.top, barW, ca.bottom - ca.top);\n    ctx.fillStyle = t.inkSoft;\n    ctx.font = \"14px sans-serif\";\n    ctx.textAlign = \"left\";\n    ctx.textBaseline = \"middle\";\n    for (const level of levels) {\n      const y = toY(level);\n      ctx.beginPath();\n      ctx.moveTo(barX + barW, y);\n      ctx.lineTo(barX + barW + 6, y);\n      ctx.stroke();\n      ctx.fillText(String(level), barX + barW + 10, y);\n    }\n    ctx.fillStyle = t.ink;\n    ctx.font = \"16px sans-serif\";\n    ctx.textAlign = \"center\";\n    ctx.translate(barX + barW + 54, (ca.top + ca.bottom) / 2);\n    ctx.rotate(-Math.PI / 2);\n    ctx.fillText(Z, 0, 0);\n    ctx.restore();\n  },\n};\n\nconst canvas = document.createElement(\"canvas\");\ndocument.getElementById(\"container\").appendChild(canvas);\n\nnew Chart(canvas, {\n  type: \"scatter\",\n  data: { datasets },\n  options: {\n    responsive: true,\n    maintainAspectRatio: false,\n    animation: false,\n    layout: { padding: { top: 42, right: 136, bottom: 42, left: 8 } },\n    interaction: { mode: \"nearest\", intersect: true },\n    plugins: {\n      title: {\n        display: true,\n        text: \"contour-basic · javascript · chartjs · anyplot.ai\",\n        color: t.ink,\n        font: { size: 22, weight: \"bold\" },\n        padding: { top: 12, bottom: 18 },\n      },\n      legend: { display: false },\n      tooltip: {\n        callbacks: {\n          title: () => \"\",\n          label: (item) => `${Z} = ${item.dataset.label}`,\n        },\n      },\n    },\n    // The band fill covers the plot area, so grid lines are off and the axis lines draw above the datasets\n    scales: {\n      x: {\n        type: \"linear\",\n        min: xs[0],\n        max: xs[xs.length - 1],\n        ticks: { color: t.inkSoft, font: { size: 14 } },\n        grid: { display: false },\n        border: { color: t.inkSoft, z: 1 },\n        title: { display: true, text: X, color: t.ink, font: { size: 16 } },\n      },\n      y: {\n        type: \"linear\",\n        min: ys[0],\n        max: ys[ys.length - 1],\n        ticks: { color: t.inkSoft, font: { size: 14 } },\n        grid: { display: false },\n        border: { color: t.inkSoft, z: 1 },\n        title: { display: true, text: Y, color: t.ink, font: { size: 16 } },\n      },\n    },\n  },\n  plugins: [bandFillPlugin, colorBarPlugin],\n});\n"}