{"spec_id":"heatmap-adjacency","library":"muix","language":"javascript","code":"// anyplot.ai\n// heatmap-adjacency: Network Adjacency Matrix Heatmap\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 89/100 | Updated: 2026-11-08\n//# anyplot-orientation: square\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ContinuousColorLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\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 TITLE = \"heatmap-adjacency · javascript · muix · anyplot.ai\";\nconst TITLE_H = 96;\nconst LEGEND_W = 190;\nconst X_AXIS_H = 34;\nconst Y_AXIS_W = 64;\nconst TEAM_LABEL_H = 44;\n\n// Columns: set these to your data's column names\nconst SOURCE = \"Source\"; // role: source\nconst TARGET = \"Target\"; // role: target\nconst WEIGHT = \"Shared threads per month\"; // role: weight\nconst SOURCE_TEAM = \"Source team\"; // role: extra\nconst TARGET_TEAM = \"Target team\"; // role: extra\n\n// Data: replace this block with your own records, one object per row\n// Undirected collaboration network of 20 people in four teams: same-team pairs link often and\n// strongly, cross-team pairs rarely and weakly; one row per linked pair\nconst data = (() => {\n  let s = 42 >>> 0;\n  const random = () => {\n    s = (Math.imul(1664525, s) + 1013904223) >>> 0;\n    return s / 4294967295;\n  };\n  const teams = [\n    { name: \"Engineering\", members: [\"Ava\", \"Noah\", \"Mia\", \"Liam\", \"Zoe\"] },\n    { name: \"Design\", members: [\"Ivy\", \"Theo\", \"Nora\", \"Omar\", \"Luca\"] },\n    { name: \"Product\", members: [\"Maya\", \"Eli\", \"Ruby\", \"Finn\", \"Sara\"] },\n    { name: \"Marketing\", members: [\"Nina\", \"Cole\", \"Ana\", \"Drew\", \"Wes\"] },\n  ];\n  const people = teams.flatMap((team) => team.members.map((name) => ({ name, team: team.name })));\n  const rows: Record<string, string | number>[] = [];\n  people.forEach((a, i) => {\n    people.slice(i + 1).forEach((b) => {\n      const sameTeam = a.team === b.team;\n      const linkRoll = random();\n      let weight = 0;\n      if (sameTeam && linkRoll < 0.85) weight = Math.round(35 + random() * 65);\n      else if (!sameTeam && linkRoll < 0.22) weight = Math.round(5 + random() * 30);\n      if (weight > 0) {\n        rows.push({ [SOURCE]: a.name, [TARGET]: b.name, [WEIGHT]: weight, [SOURCE_TEAM]: a.team, [TARGET_TEAM]: b.team });\n      }\n    });\n  });\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst edges = data.filter((d) => Number.isFinite(Number(d[WEIGHT])));\n\n// Nodes from both endpoint columns (first appearance in the source column, then the target column),\n// grouped by team to expose the blocks along the diagonal\nconst teamOf = new Map<string, string>();\nedges.forEach((d) => teamOf.set(String(d[SOURCE]), String(d[SOURCE_TEAM])));\nedges.forEach((d) => teamOf.set(String(d[TARGET]), String(d[TARGET_TEAM])));\nconst teams = [...new Set([...teamOf.values()])];\nconst nodes = teams.flatMap((team) => [...teamOf.keys()].filter((name) => teamOf.get(name) === team));\n\n// Undirected graph: each pair fills both triangles; an absent pair keeps no entry\nconst weightOf = new Map<string, number>();\nedges.forEach((d) => {\n  weightOf.set(`${d[SOURCE]}|${d[TARGET]}`, Number(d[WEIGHT]));\n  weightOf.set(`${d[TARGET]}|${d[SOURCE]}`, Number(d[WEIGHT]));\n});\nconst cells = nodes.flatMap((row) =>\n  nodes.map((col) => ({ key: `${row}|${col}`, row, col, weight: weightOf.get(`${row}|${col}`) })),\n);\nconst minWeight = Math.min(...weightOf.values());\nconst maxWeight = Math.max(...weightOf.values());\n\n// Team blocks along the diagonal: first and last node of each team\nconst blocks = teams.map((team) => {\n  const members = nodes.filter((name) => teamOf.get(name) === team);\n  return { team, first: members[0], last: members[members.length - 1] };\n});\nconst strongest = edges.filter((d) => Number(d[WEIGHT]) === maxWeight);\nconst subtitle = `${nodes.length} nodes in ${teams.length} teams · ${edges.length} undirected links, both triangles filled · outlined: strongest link (${maxWeight}), ${strongest.map((d) => `${d[SOURCE]}–${d[TARGET]}`).join(\", \")}`;\n\nfunction AdjacencyLayer() {\n  const xScale = useXScale() as unknown as ((v: string) => number) & { bandwidth: () => number; step: () => number };\n  const yScale = useYScale() as unknown as ((v: string) => number) & { bandwidth: () => number; step: () => 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 halfGap = (xScale.step() - cellW) / 2;\n  return (\n    <g>\n      {cells.map((c) => (\n        <rect\n          key={c.key}\n          x={xScale(c.col)}\n          y={yScale(c.row)}\n          width={cellW}\n          height={cellH}\n          fill={c.weight === undefined ? t.elevatedBg : colorScale(c.weight)}\n          stroke={c.weight === maxWeight ? t.ink : \"none\"}\n          strokeWidth={c.weight === maxWeight ? 2.5 : 0}\n        />\n      ))}\n      {blocks.slice(1).map((b) => (\n        <g key={b.team}>\n          <line\n            x1={xScale(b.first) - halfGap}\n            x2={xScale(b.first) - halfGap}\n            y1={top}\n            y2={top + height}\n            stroke={t.inkSoft}\n            strokeWidth={2}\n          />\n          <line\n            x1={left}\n            x2={left + width}\n            y1={yScale(b.first) - halfGap}\n            y2={yScale(b.first) - halfGap}\n            stroke={t.inkSoft}\n            strokeWidth={2}\n          />\n        </g>\n      ))}\n      {blocks.map((b) => (\n        <text\n          key={`label-${b.team}`}\n          x={(xScale(b.first) + xScale(b.last) + cellW) / 2}\n          y={top + height + 28}\n          textAnchor=\"middle\"\n          fontSize={15}\n          fontWeight={600}\n          fill={t.inkSoft}\n        >\n          {b.team}\n        </text>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartW = width - LEGEND_W;\n  const chartH = height - TITLE_H;\n  // Equal px per node on both axes: the matrix is a square of the smaller available side\n  const availW = chartW - 16 - Y_AXIS_W - 12;\n  const availH = chartH - 8 - X_AXIS_H - TEAM_LABEL_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\", lineHeight: 1.35 }}>{subtitle}</Typography>\n      </Box>\n      <ChartsDataProvider\n        width={chartW}\n        height={chartH}\n        series={[]}\n        skipAnimation\n        margin={{ top: 8, left: 16, right: 12 + availW - side, bottom: TEAM_LABEL_H + availH - side }}\n        xAxis={[\n          {\n            scaleType: \"band\",\n            data: nodes,\n            position: \"top\",\n            height: X_AXIS_H,\n            categoryGapRatio: 0.06,\n            disableLine: true,\n            disableTicks: true,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"band\",\n            data: nodes,\n            width: Y_AXIS_W,\n            categoryGapRatio: 0.06,\n            disableLine: true,\n            disableTicks: true,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        zAxis={[{ colorMap: { type: \"continuous\", min: minWeight, max: maxWeight, color: [t.seq[0], t.seq[1]] } }]}\n      >\n        <ChartsWrapper\n          legendPosition={{ vertical: \"middle\", horizontal: \"end\" }}\n          legendDirection=\"vertical\"\n          sx={{ width, height: chartH }}\n        >\n          <Box\n            sx={{\n              gridArea: \"legend\",\n              width: LEGEND_W,\n              height: 520,\n              display: \"flex\",\n              flexDirection: \"column\",\n              alignItems: \"center\",\n              pr: \"24px\",\n              boxSizing: \"border-box\",\n            }}\n          >\n            <Typography sx={{ fontSize: 15, color: t.ink, textAlign: \"center\", lineHeight: 1.3, maxWidth: 160, mb: \"10px\", textWrap: \"balance\" }}>\n              {WEIGHT}\n            </Typography>\n            <ContinuousColorLegend\n              direction=\"vertical\"\n              thickness={20}\n              labelPosition=\"end\"\n              sx={{ flex: 1, color: t.inkSoft, fontSize: 14 }}\n            />\n          </Box>\n          <ChartsSurface>\n            <AdjacencyLayer />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </Box>\n  );\n}\n"}