{"spec_id":"heatmap-correlation","library":"muix","language":"javascript","code":"// anyplot.ai\n// heatmap-correlation: Correlation Matrix Heatmap\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n//# anyplot-orientation: square\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, useZColorScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst R_MIN = -1; // the colour bar spans the full correlation range\nconst R_MAX = 1;\nconst COLORBAR_TICKS = [-1, -0.5, 0, 0.5, 1];\nconst TITLE = \"heatmap-correlation · javascript · muix · anyplot.ai\";\nconst TITLE_H = 92;\nconst Y_AXIS_W = 130;\nconst X_AXIS_H = 48;\nconst COLORBAR_AREA_W = 150;\nconst DIV_RGB = t.div.map((hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)));\n\n// Columns: set these to your data's column names\nconst ASSET = \"Asset class\"; // role: variables\nconst CORRELATION = \"Correlation (Pearson r)\"; // role: correlation_matrix\n\n// Data: replace this block with your own records, one row of the square matrix per object,\n// keyed by the row's name and one column per variable\n// Correlations of monthly returns across six asset classes in a diversified portfolio\nconst data = [\n  { [ASSET]: \"Equities\", Equities: 1.0, Bonds: -0.35, \"Real Estate\": 0.55, Commodities: 0.2, Gold: -0.1, Cash: -0.05 },\n  { [ASSET]: \"Bonds\", Equities: -0.35, Bonds: 1.0, \"Real Estate\": 0.15, Commodities: -0.2, Gold: 0.3, Cash: 0.1 },\n  { [ASSET]: \"Real Estate\", Equities: 0.55, Bonds: 0.15, \"Real Estate\": 1.0, Commodities: 0.25, Gold: 0.05, Cash: -0.15 },\n  { [ASSET]: \"Commodities\", Equities: 0.2, Bonds: -0.2, \"Real Estate\": 0.25, Commodities: 1.0, Gold: 0.65, Cash: -0.1 },\n  { [ASSET]: \"Gold\", Equities: -0.1, Bonds: 0.3, \"Real Estate\": 0.05, Commodities: 0.65, Gold: 1.0, Cash: 0.2 },\n  { [ASSET]: \"Cash\", Equities: -0.05, Bonds: 0.1, \"Real Estate\": -0.15, Commodities: -0.1, Gold: 0.2, Cash: 1.0 },\n];\n\n// Plot: reads only data and the constants above\n// The variable list comes from the row labels and the column keys, in order of first appearance\nconst variables = [\n  ...new Set([...data.map((d) => String(d[ASSET])), ...data.flatMap((d) => Object.keys(d).filter((k) => k !== ASSET))]),\n];\nconst rowOf = new Map(data.map((d) => [String(d[ASSET]), d]));\n\n// The matrix is symmetric: show the diagonal and the lower triangle, mask the mirrored upper triangle\nconst cells = variables.flatMap((row, i) =>\n  variables.slice(0, i + 1).map((col) => ({ key: `${row}|${col}`, row, col, r: Number(rowOf.get(row)?.[col]) })),\n);\nconst offDiagonal = cells.filter((c) => c.row !== c.col && Number.isFinite(c.r));\nconst strongest = offDiagonal.reduce((best, c) => (Math.abs(c.r) > Math.abs(best.r) ? c : best), offDiagonal[0]);\nconst subtitle = `${variables.length} × ${variables.length} matrix, lower triangle shown (the upper one mirrors it) · strongest pair: ${strongest.row} – ${strongest.col}, r = ${strongest.r.toFixed(2)}`;\n\nfunction CorrelationLayer() {\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 unknown as (v: number) => string;\n  const { left, top, width, height } = useDrawingArea();\n  const cellW = xScale.bandwidth();\n  const cellH = yScale.bandwidth();\n  const barX = left + width + 36;\n  const barW = 22;\n  return (\n    <g>\n      <defs>\n        <linearGradient id=\"correlation-colorbar\" 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      {cells\n        .filter((c) => Number.isFinite(c.r))\n        .map((c) => {\n          const fill = colorScale(c.r);\n          const [r, g, b] = (fill.match(/\\d+/g) ?? []).map(Number);\n          const luminance = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;\n          return (\n            <g key={c.key}>\n              <rect x={xScale(c.col)} y={yScale(c.row)} width={cellW} height={cellH} fill={fill} stroke={t.grid} strokeWidth={1} />\n              <text\n                x={xScale(c.col) + cellW / 2}\n                y={yScale(c.row) + cellH / 2}\n                textAnchor=\"middle\"\n                dominantBaseline=\"central\"\n                fontSize={24}\n                fontWeight={600}\n                fill={luminance > 0.5 ? \"#1A1A17\" : \"#FAF8F1\"}\n              >\n                {c.r.toFixed(2)}\n              </text>\n            </g>\n          );\n        })}\n      <rect x={barX} y={top} width={barW} height={height} fill=\"url(#correlation-colorbar)\" stroke={t.inkSoft} strokeWidth={1} />\n      {COLORBAR_TICKS.map((tick) => {\n        const ty = top + height * (1 - (tick - R_MIN) / (R_MAX - R_MIN));\n        return (\n          <g key={tick}>\n            <line x1={barX + barW} x2={barX + barW + 6} y1={ty} y2={ty} stroke={t.inkSoft} strokeWidth={1} />\n            <text x={barX + barW + 10} y={ty} fontSize={14} fill={t.inkSoft} dominantBaseline=\"central\">\n              {tick.toFixed(1)}\n            </text>\n          </g>\n        );\n      })}\n      <text\n        x={barX + barW + 66}\n        y={top + height / 2}\n        fontSize={16}\n        fill={t.ink}\n        textAnchor=\"middle\"\n        transform={`rotate(-90, ${barX + barW + 66}, ${top + height / 2})`}\n      >\n        {CORRELATION}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartH = height - TITLE_H;\n  // Square cells: the matrix is a square of the smaller available side, centred vertically\n  const availW = width - 16 - Y_AXIS_W - COLORBAR_AREA_W;\n  const availH = chartH - 32 - X_AXIS_H;\n  const side = Math.min(availW, availH);\n  return (\n    <Box sx={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <Box sx={{ height: TITLE_H, pt: \"20px\", px: \"24px\", textAlign: \"center\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, mt: \"6px\" }}>{subtitle}</Typography>\n      </Box>\n      <ChartsContainer\n        width={width}\n        height={chartH}\n        series={[]}\n        skipAnimation\n        margin={{\n          top: 16 + (availH - side) / 2,\n          bottom: 16 + (availH - side) / 2,\n          left: 16,\n          right: COLORBAR_AREA_W + availW - side,\n        }}\n        xAxis={[\n          {\n            scaleType: \"band\",\n            data: variables,\n            height: X_AXIS_H,\n            categoryGapRatio: 0.04,\n            disableLine: true,\n            disableTicks: true,\n            tickLabelStyle: { fontSize: 16, fill: t.inkSoft },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"band\",\n            data: variables,\n            width: Y_AXIS_W,\n            categoryGapRatio: 0.04,\n            disableLine: true,\n            disableTicks: true,\n            tickLabelStyle: { fontSize: 16, fill: t.inkSoft },\n          },\n        ]}\n        zAxis={[\n          {\n            colorMap: {\n              type: \"continuous\",\n              min: R_MIN,\n              max: R_MAX,\n              // Three-stop Imprint diverging ramp: red at −1, the page colour at 0, blue at +1\n              color: (f: number) => {\n                const [from, to, share] = f < 0.5 ? [DIV_RGB[0], DIV_RGB[1], f * 2] : [DIV_RGB[1], DIV_RGB[2], f * 2 - 1];\n                return `rgb(${from.map((c: number, i: number) => Math.round(c + (to[i] - c) * share)).join(\", \")})`;\n              },\n            },\n          },\n        ]}\n      >\n        <CorrelationLayer />\n        <ChartsXAxis />\n        <ChartsYAxis />\n      </ChartsContainer>\n    </Box>\n  );\n}\n"}