{"spec_id":"heatmap-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// heatmap-basic: Basic Heatmap\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 85/100 | Updated: 2026-10-24\n//# anyplot-orientation: square\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, useZColorScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst SIZE = window.ANYPLOT_SIZE;\nconst TITLE = \"heatmap-basic · javascript · muix · anyplot.ai\";\nconst DOMAIN_MIN = -1;\nconst DOMAIN_MAX = 1;\nconst COLORBAR_TICKS = [-1.0, -0.5, 0.0, 0.5, 1.0];\nconst MARGIN = { top: 104, right: 138, bottom: 32, left: 20 };\n\n// Columns: set these to your data's column names\nconst COL_METRIC = \"Column metric\"; // role: x\nconst ROW_METRIC = \"Row metric\"; // role: y\nconst CORRELATION = \"Correlation coefficient\"; // role: value\n\n// Data: replace this block with your own records\nconst METRIC_NAMES = [\n  \"Revenue\",\n  \"Marketing\",\n  \"CSAT\",\n  \"Headcount\",\n  \"R&D\",\n  \"Mkt Share\",\n  \"OpEx\",\n  \"Churn\",\n];\n\nconst UPPER_TRIANGLE_ROWS = [\n  \"0.72,0.45,0.68,0.55,0.81,0.60,-0.52\",\n  \"0.30,0.40,0.25,0.66,0.58,-0.20\",\n  \"0.35,0.28,0.50,-0.10,-0.78\",\n  \"0.62,0.47,0.71,-0.18\",\n  \"0.58,0.33,-0.25\",\n  \"0.40,-0.44\",\n  \"0.15\",\n];\n\nconst parsedUpper = UPPER_TRIANGLE_ROWS.map((s) => s.split(\",\").map(Number));\nconst nMetrics = METRIC_NAMES.length;\nconst data: Record<string, string | number>[] = [];\n\nfor (let row = 0; row < nMetrics; row++) {\n  for (let col = 0; col < nMetrics; col++) {\n    const minIdx = Math.min(row, col);\n    const maxIdx = Math.max(row, col);\n    const val = row === col ? 1.0 : parsedUpper[minIdx][maxIdx - minIdx - 1];\n    data.push({\n      [ROW_METRIC]: METRIC_NAMES[row],\n      [COL_METRIC]: METRIC_NAMES[col],\n      [CORRELATION]: val,\n    });\n  }\n}\n\n// Plot: reads only data and the constants above\nconst xCategories = Array.from(new Set(data.map((r) => String(r[COL_METRIC]))));\nconst yCategories = Array.from(new Set(data.map((r) => String(r[ROW_METRIC]))));\n\nconst cells = data.map((row, idx) => ({\n  id: `${idx}-${row[ROW_METRIC]}-${row[COL_METRIC]}`,\n  x: String(row[COL_METRIC]),\n  y: String(row[ROW_METRIC]),\n  value: Number(row[CORRELATION]),\n}));\n\n// Three-stop imprint_div ramp: red at 0, page-colored midpoint at 0.5, blue at 1\nconst hexToRgb = (hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));\nconst DIV_STOPS = t.div.map(hexToRgb);\n\nfunction divergingColor(frac: number): string {\n  const f = Math.min(1, Math.max(0, frac));\n  const [from, to, local] = f < 0.5 ? [DIV_STOPS[0], DIV_STOPS[1], f * 2] : [DIV_STOPS[1], DIV_STOPS[2], (f - 0.5) * 2];\n  const [r, g, b] = from.map((c, i) => Math.round(c + (to[i] - c) * local));\n  return `rgb(${r}, ${g}, ${b})`;\n}\n\nfunction HeatmapCells() {\n  const xScale = useXScale() as unknown as ((v: string) => number) & { bandwidth: () => number };\n  const yScale = useYScale() as unknown as ((v: string) => number) & { bandwidth: () => number };\n  const colorScale = useZColorScale() as (v: number) => string;\n  const { left, top, width, height } = useDrawingArea();\n\n  const bw = xScale.bandwidth();\n  const bh = yScale.bandwidth();\n  const barX = left + width + 28;\n  const barW = 20;\n\n  return (\n    <g>\n      <defs>\n        <linearGradient id=\"basicHeatmapDivGrad\" x1=\"0\" y1=\"1\" x2=\"0\" y2=\"0\">\n          <stop offset=\"0%\" stopColor={t.div[0]} />\n          <stop offset=\"50%\" stopColor={t.div[1]} />\n          <stop offset=\"100%\" stopColor={t.div[2]} />\n        </linearGradient>\n      </defs>\n\n      {cells.map((cell) => {\n        const x = xScale(cell.x);\n        const y = yScale(cell.y);\n        const fill = colorScale(cell.value);\n        const [r, g, b] = (fill.match(/[\\d.]+/g) ?? [\"128\", \"128\", \"128\"]).map(Number);\n        const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n        const textFill = luminance > 140 ? \"#1A1A17\" : \"#FAF8F1\";\n\n        return (\n          <g key={cell.id}>\n            <rect x={x} y={y} width={bw} height={bh} fill={fill} rx={4} />\n            <text\n              x={x + bw / 2}\n              y={y + bh / 2}\n              fontSize={16}\n              fontWeight={600}\n              fill={textFill}\n              textAnchor=\"middle\"\n              dominantBaseline=\"central\"\n            >\n              {cell.value.toFixed(2)}\n            </text>\n          </g>\n        );\n      })}\n\n      {/* Diverging colorbar legend */}\n      <rect x={barX} y={top} width={barW} height={height} fill=\"url(#basicHeatmapDivGrad)\" rx={3} />\n      {COLORBAR_TICKS.map((tick) => {\n        const ty = top + height * (1 - (tick - DOMAIN_MIN) / (DOMAIN_MAX - DOMAIN_MIN));\n        return (\n          <g key={tick}>\n            <line x1={barX + barW} y1={ty} x2={barX + barW + 6} y2={ty} stroke={t.inkSoft} strokeWidth={1} />\n            <text\n              x={barX + barW + 10}\n              y={ty}\n              fontSize={14}\n              fill={t.inkSoft}\n              dominantBaseline=\"central\"\n            >\n              {tick.toFixed(1)}\n            </text>\n          </g>\n        );\n      })}\n      <text\n        x={barX + barW + 58}\n        y={top + height / 2}\n        fontSize={15}\n        fill={t.inkSoft}\n        textAnchor=\"middle\"\n        transform={`rotate(-90, ${barX + barW + 58}, ${top + height / 2})`}\n      >\n        {CORRELATION}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const subtitle = `${CORRELATION} matrix (${xCategories.length} × ${yCategories.length})`;\n\n  return (\n    <ChartsContainer\n      width={SIZE.width}\n      height={SIZE.height}\n      series={[]}\n      margin={MARGIN}\n      skipAnimation\n      xAxis={[\n        {\n          scaleType: \"band\",\n          data: xCategories,\n          height: 54,\n          categoryGapRatio: 0.08,\n          disableLine: true,\n          disableTicks: true,\n          tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n        },\n      ]}\n      yAxis={[\n        {\n          scaleType: \"band\",\n          data: yCategories,\n          width: 124,\n          categoryGapRatio: 0.08,\n          disableLine: true,\n          disableTicks: true,\n          tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n        },\n      ]}\n      zAxis={[\n        {\n          colorMap: {\n            type: \"continuous\",\n            min: DOMAIN_MIN,\n            max: DOMAIN_MAX,\n            color: divergingColor,\n          },\n        },\n      ]}\n    >\n      <HeatmapCells />\n      <ChartsXAxis />\n      <ChartsYAxis />\n      <text\n        x={SIZE.width / 2}\n        y={42}\n        fontSize={22}\n        fontWeight={600}\n        fill={t.ink}\n        textAnchor=\"middle\"\n      >\n        {TITLE}\n      </text>\n      <text\n        x={SIZE.width / 2}\n        y={68}\n        fontSize={15}\n        fill={t.inkSoft}\n        textAnchor=\"middle\"\n      >\n        {subtitle}\n      </text>\n    </ChartsContainer>\n  );\n}\n"}