{"spec_id":"contour-filled","library":"echarts","language":"javascript","code":"// anyplot.ai\n// contour-filled: Filled Contour Plot\n// Library: echarts 6.1.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-09\n\n//# anyplot-orientation: square\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst LEVEL_TARGET = 10; // aim for about this many evenly stepped contour levels\n\n// Columns: set these to your data's column names\nconst EAST = \"Distance East–West (km)\"; // role: x\nconst NORTH = \"Distance North–South (km)\"; // role: y\nconst RAIN = \"Rainfall intensity (mm/hr)\"; // role: z\n\n// Data: replace this block with your own records, one object per grid point\n// Combined rainfall intensity of two overlapping storm cells over a 100 km x 100 km\n// region, sampled on a regular 100 x 100 grid. Each storm cell is a Gaussian:\n// [centre east, centre north, sigma, peak intensity in mm/hr].\nconst gridSize = 100;\nconst storms = [\n  [-25, -18, 11, 45],\n  [25, 20, 13, 30],\n];\nconst data = [];\nfor (let i = 0; i < gridSize; i++) {\n  for (let j = 0; j < gridSize; j++) {\n    const east = Math.round((-50 + (100 * i) / (gridSize - 1)) * 100) / 100;\n    const north = Math.round((-50 + (100 * j) / (gridSize - 1)) * 100) / 100;\n    const rain = storms.reduce(\n      (sum, [cx, cy, sigma, peak]) =>\n        sum + peak * Math.exp(-((east - cx) ** 2 + (north - cy) ** 2) / (2 * sigma * sigma)),\n      0,\n    );\n    data.push({ [EAST]: east, [NORTH]: north, [RAIN]: Math.round(rain * 10) / 10 });\n  }\n}\n\n// Plot: reads only data and the constants above\n// Rebuild the regular grid from the records; a missing grid point stays null.\nconst xs = [...new Set(data.map((d) => d[EAST]))].sort((a, b) => a - b);\nconst ys = [...new Set(data.map((d) => d[NORTH]))].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 z = xs.map(() => ys.map(() => null));\ndata.forEach((d) => {\n  z[xIndex.get(d[EAST])][yIndex.get(d[NORTH])] = d[RAIN];\n});\n\n// Round steps (1, 2, 2.5 or 5 times a power of ten) for the levels and both axes' ticks\nconst values = data.map((d) => d[RAIN]).filter((v) => v != null);\nconst zMin = Math.min(...values);\nconst zMax = Math.max(...values);\nconst [levelStep, xTick, yTick] = [\n  [zMax - zMin, LEVEL_TARGET],\n  [xs.at(-1) - xs[0], 4],\n  [ys.at(-1) - ys[0], 4],\n].map(([span, parts]) => {\n  const raw = span / parts;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  return [1, 2, 2.5, 5, 10].map((m) => m * magnitude).find((s) => s >= raw);\n});\n\n// Evenly stepped levels that span the data's range\nconst levelLow = Math.floor(zMin / levelStep) * levelStep;\nconst levelCount = Math.ceil((zMax - levelLow) / levelStep);\nconst levels = Array.from({ length: levelCount + 1 }, (_, k) => +(levelLow + k * levelStep).toFixed(6));\n\n// Marching triangles: every grid cell splits into two triangles, the field is linear\n// on each, so the region above a level and the level's isoline are exact polygons and\n// segments. Layer k holds the region at or above levels[k], painted in the colour of\n// band k; stacking the layers from low to high leaves each point in the colour of its\n// band, with smooth boundaries and no seams between bands.\nconst layers = levels.slice(0, -1).map(() => []);\nconst isolines = [];\nfor (let i = 0; i + 1 < xs.length; i++) {\n  for (let j = 0; j + 1 < ys.length; j++) {\n    const a = [xs[i], ys[j], z[i][j]];\n    const b = [xs[i + 1], ys[j], z[i + 1][j]];\n    const c = [xs[i + 1], ys[j + 1], z[i + 1][j + 1]];\n    const d = [xs[i], ys[j + 1], z[i][j + 1]];\n    for (const tri of [\n      [a, b, c],\n      [a, c, d],\n    ]) {\n      if (tri.some((p) => p[2] == null)) continue;\n      const triMax = Math.max(...tri.map((p) => p[2]));\n      layers.forEach((layer, k) => {\n        const level = levels[k];\n        if (triMax < level) return;\n        const polygon = [];\n        const crossings = [];\n        tri.forEach((p, n) => {\n          const q = tri[(n + 1) % 3];\n          if (p[2] >= level) polygon.push(p);\n          if (p[2] >= level !== q[2] >= level) {\n            const s = (level - p[2]) / (q[2] - p[2]);\n            const cross = [p[0] + s * (q[0] - p[0]), p[1] + s * (q[1] - p[1])];\n            polygon.push(cross);\n            crossings.push(cross);\n          }\n        });\n        layer.push(polygon);\n        if (k > 0 && crossings.length === 2) isolines.push(crossings);\n      });\n    }\n  }\n}\n\nconst titleText = \"Storm Rainfall Intensity · contour-filled · javascript · echarts · anyplot.ai\";\nconst titleSize = Math.max(15, Math.round(22 * Math.min(1, 67 / titleText.length)));\n\n// Colour bar: one swatch per band, split by hairline gaps, centred beside the field\nconst gridBox = { left: 110, top: 145, width: 880, height: 880 };\nconst swatchGap = 2;\nconst swatchHeight = Math.min(60, Math.floor(600 / layers.length)) - swatchGap;\nconst barTop = gridBox.top + (gridBox.height - (swatchHeight + swatchGap) * layers.length) / 2;\n\nconst axisStyle = {\n  nameLocation: \"middle\",\n  nameTextStyle: { color: t.ink, fontSize: 18 },\n  axisLabel: { color: t.inkSoft, fontSize: 15 },\n  axisLine: { show: false },\n  axisTick: { show: false },\n  splitLine: { show: false },\n};\n\nconst chart = echarts.init(document.getElementById(\"container\"));\n\nchart.setOption({\n  animation: false,\n  backgroundColor: \"transparent\",\n\n  title: [\n    {\n      text: titleText,\n      left: \"center\",\n      top: 24,\n      textStyle: { color: t.ink, fontSize: titleSize, fontWeight: \"bold\" },\n    },\n    {\n      text: RAIN.replace(\" (\", \"\\n(\"),\n      left: gridBox.left + gridBox.width + 40,\n      top: barTop - 58,\n      textStyle: { color: t.ink, fontSize: 15, fontWeight: \"normal\", lineHeight: 20 },\n    },\n  ],\n\n  grid: gridBox,\n\n  xAxis: {\n    ...axisStyle,\n    type: \"value\",\n    name: EAST,\n    nameGap: 40,\n    min: xs[0],\n    max: xs.at(-1),\n    interval: xTick,\n  },\n\n  yAxis: {\n    ...axisStyle,\n    type: \"value\",\n    name: NORTH,\n    nameGap: 55,\n    min: ys[0],\n    max: ys.at(-1),\n    interval: yTick,\n  },\n\n  // Piecewise colour bar on the Imprint sequential ramp, one piece per band\n  visualMap: {\n    type: \"piecewise\",\n    seriesIndex: 0,\n    dimension: 2,\n    pieces: layers.map((_, k) => ({\n      gte: levels[k],\n      lt: levels[k + 1],\n      label: `${levels[k]}–${levels[k + 1]}`,\n    })),\n    inRange: { color: t.seq },\n    orient: \"vertical\",\n    align: \"left\",\n    left: gridBox.left + gridBox.width + 40,\n    top: barTop,\n    itemSymbol: \"rect\",\n    itemWidth: 26,\n    itemHeight: swatchHeight,\n    itemGap: swatchGap,\n    textGap: 12,\n    textStyle: { color: t.inkSoft, fontSize: 15 },\n    hoverLink: false,\n  },\n\n  series: [\n    {\n      // Filled bands: one path per layer, painted from the lowest level up\n      type: \"custom\",\n      silent: true,\n      encode: { x: 0, y: 1 },\n      data: layers.map((_, k) => [xs[0], ys[0], (levels[k] + levels[k + 1]) / 2]),\n      renderItem: (params, api) => ({\n        type: \"path\",\n        shape: {\n          pathData: layers[params.dataIndex]\n            .map(\n              (polygon) =>\n                polygon\n                  .map((p, n) => {\n                    const [px, py] = api.coord(p);\n                    return `${n ? \"L\" : \"M\"}${px.toFixed(2)} ${py.toFixed(2)}`;\n                  })\n                  .join(\"\") + \"Z\",\n            )\n            .join(\"\"),\n        },\n        style: { fill: api.visual(\"color\") },\n      }),\n    },\n    {\n      // Thin contour lines along every inner band boundary\n      type: \"custom\",\n      silent: true,\n      encode: { x: 0, y: 1 },\n      data: [[xs[0], ys[0]]],\n      renderItem: (params, api) => ({\n        type: \"path\",\n        shape: {\n          pathData: isolines\n            .map(([p, q]) => {\n              const [px, py] = api.coord(p);\n              const [qx, qy] = api.coord(q);\n              return `M${px.toFixed(2)} ${py.toFixed(2)}L${qx.toFixed(2)} ${qy.toFixed(2)}`;\n            })\n            .join(\"\"),\n        },\n        style: { fill: null, stroke: t.ink, lineWidth: 1, opacity: 0.4 },\n      }),\n    },\n  ],\n\n  tooltip: { show: false },\n});\n"}