{"spec_id":"confusion-matrix","library":"muix","language":"javascript","code":"// anyplot.ai\n// confusion-matrix: Confusion Matrix Heatmap\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-23\n//# anyplot-orientation: square\n\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ScatterChart } from \"@mui/x-charts/ScatterChart\";\nimport { ContinuousColorLegend } from \"@mui/x-charts/ChartsLegend\";\n\nconst tokens = window.ANYPLOT_TOKENS;\n\n// Columns: set these to your data's column names\nconst TRUE_LABELS = \"True Label\"; // role: true_labels\nconst PREDICTED_LABELS = \"Predicted Label\"; // role: predicted_labels\n\n// Data: replace this block with your own records, one object per row\nconst data = (() => {\n  const sampleClasses = [\"Paper\", \"Glass\", \"Metal\", \"Plastic\", \"Organic\"];\n  const countsMatrix = [\n    [182, 4, 1, 6, 3],\n    [5, 151, 3, 9, 2],\n    [1, 4, 142, 11, 0],\n    [7, 9, 12, 158, 5],\n    [2, 1, 0, 6, 176],\n  ];\n  const rows: {\n    [TRUE_LABELS]: string;\n    [PREDICTED_LABELS]: string;\n  }[] = [];\n  sampleClasses.forEach((trueClass, r) => {\n    sampleClasses.forEach((predictedClass, c) => {\n      const n = countsMatrix[r][c];\n      for (let k = 0; k < n; k += 1) {\n        rows.push({\n          [TRUE_LABELS]: trueClass,\n          [PREDICTED_LABELS]: predictedClass,\n        });\n      }\n    });\n  });\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\n// Every class seen as a true or a predicted label, in order of first appearance,\n// so a class that is only ever predicted still gets its row and column.\nconst classes = Array.from(\n  new Set(data.flatMap((d) => [d[TRUE_LABELS], d[PREDICTED_LABELS]])),\n);\n\nconst pairCounts = new Map<string, number>();\nconst rowTotals = new Map<string, number>();\ndata.forEach((d) => {\n  const tLabel = d[TRUE_LABELS];\n  const pLabel = d[PREDICTED_LABELS];\n  const key = `${tLabel}__${pLabel}`;\n  pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);\n  rowTotals.set(tLabel, (rowTotals.get(tLabel) ?? 0) + 1);\n});\n\nconst points: {\n  id: string;\n  x: string;\n  y: string;\n  z: number;\n  count: number;\n  rowPct: number;\n}[] = [];\nlet maxCount = 0;\nclasses.forEach((trueClass, row) => {\n  const rowTotal = rowTotals.get(trueClass) ?? 1;\n  classes.forEach((predictedClass, col) => {\n    const count = pairCounts.get(`${trueClass}__${predictedClass}`) ?? 0;\n    if (count > maxCount) maxCount = count;\n    points.push({\n      id: `${row}-${col}`,\n      x: predictedClass,\n      y: trueClass,\n      z: count,\n      count,\n      rowPct: Math.round((count / rowTotal) * 100),\n    });\n  });\n});\n\nfunction mixHex(hexA: string, hexB: string, ratio: number) {\n  const a = parseInt(hexA.slice(1), 16);\n  const b = parseInt(hexB.slice(1), 16);\n  const channel = (shift: number) => {\n    const av = (a >> shift) & 255;\n    const bv = (b >> shift) & 255;\n    return Math.round(av + (bv - av) * ratio);\n  };\n  return `#${[16, 8, 0].map((shift) => channel(shift).toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction sequentialColor(t: number) {\n  const [low, high] = tokens.seq;\n  return mixHex(low, high, Math.pow(t, 0.45));\n}\n\nfunction relativeLuminance(hex: string) {\n  const n = parseInt(hex.slice(1), 16);\n  const r = ((n >> 16) & 255) / 255;\n  const g = ((n >> 8) & 255) / 255;\n  const b = (n & 255) / 255;\n  return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n}\n\nfunction ConfusionCell(props: any) {\n  const { series, xScale, yScale, colorGetter, color } = props;\n  const cellWidth = xScale.bandwidth();\n  const cellHeight = yScale.bandwidth();\n  const countFontSize = Math.round(Math.min(cellWidth, cellHeight) * 0.2);\n  const pctFontSize = Math.round(countFontSize * 0.55);\n\n  return (\n    <g>\n      {series.data.map((point: any, i: number) => {\n        const x0 = xScale(point.x) ?? 0;\n        const y0 = yScale(point.y) ?? 0;\n        const fill = colorGetter ? colorGetter(i) : color;\n        const textFill = relativeLuminance(fill) > 0.55 ? \"#1A1A17\" : \"#F0EFE8\";\n        const isCorrect = point.x === point.y;\n        return (\n          <g key={point.id}>\n            <rect\n              x={x0}\n              y={y0}\n              width={cellWidth}\n              height={cellHeight}\n              fill={fill}\n              stroke={isCorrect ? tokens.ink : \"none\"}\n              strokeWidth={isCorrect ? 4 : 0}\n            />\n            <text\n              x={x0 + cellWidth / 2}\n              y={y0 + cellHeight / 2 - pctFontSize * 0.7}\n              textAnchor=\"middle\"\n              dominantBaseline=\"central\"\n              fontSize={countFontSize}\n              fontWeight={isCorrect ? 700 : 400}\n              fontFamily=\"inherit\"\n              fill={textFill}\n            >\n              {point.count}\n            </text>\n            <text\n              x={x0 + cellWidth / 2}\n              y={y0 + cellHeight / 2 + countFontSize * 0.6}\n              textAnchor=\"middle\"\n              dominantBaseline=\"central\"\n              fontSize={pctFontSize}\n              fontFamily=\"inherit\"\n              fill={textFill}\n              opacity={0.85}\n            >\n              {point.rowPct}%\n            </text>\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\n// Color bar with a title naming what the color and the in-cell percentages show\nfunction CountLegend({ sx, ...legendProps }: any) {\n  return (\n    <Box sx={{ gridArea: \"legend\", width: \"50%\", mb: \"20px\", mr: \"20px\", fontFamily: \"inherit\" }}>\n      <Typography sx={{ color: tokens.ink, fontSize: 16, fontWeight: 500, fontFamily: \"inherit\", mb: \"6px\" }}>\n        Count · % = share of true-class row (recall)\n      </Typography>\n      <ContinuousColorLegend {...legendProps} sx={{ ...sx, width: \"100%\" }} />\n    </Box>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const TITLE_HEIGHT = 80;\n  const RIGHT_BUFFER = 40;\n  const BOTTOM_BUFFER = 64;\n  const chartWidth = width - RIGHT_BUFFER;\n  const chartHeight = height - TITLE_HEIGHT - BOTTOM_BUFFER;\n\n  return (\n    <Box sx={{ width, height, bgcolor: tokens.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <Typography\n        sx={{\n          color: tokens.ink,\n          fontSize: 22,\n          fontWeight: 500,\n          textAlign: \"center\",\n          lineHeight: 1.2,\n          pt: \"16px\",\n          height: TITLE_HEIGHT,\n          fontFamily: \"inherit\",\n        }}\n      >\n        confusion-matrix · javascript · muix · anyplot.ai\n      </Typography>\n      <Box sx={{ flex: 1, display: \"flex\", alignItems: \"flex-start\", justifyContent: \"flex-start\" }}>\n        <ScatterChart\n          width={chartWidth}\n          height={chartHeight}\n          skipAnimation\n          disableHitArea\n          series={[\n            {\n              id: \"confusion\",\n              type: \"scatter\",\n              data: points,\n              label: \"Predictions\",\n              xAxisId: \"predicted\",\n              yAxisId: \"actual\",\n              zAxisId: \"count\",\n            },\n          ]}\n          xAxis={[\n            {\n              id: \"predicted\",\n              position: \"top\",\n              height: 84,\n              scaleType: \"band\",\n              data: classes,\n              categoryGapRatio: 0.08,\n              label: PREDICTED_LABELS,\n              labelStyle: { fontSize: 18, fill: tokens.ink, fontFamily: \"inherit\" },\n              tickLabelStyle: { fontSize: 16, fill: tokens.inkSoft, fontFamily: \"inherit\" },\n              disableTicks: true,\n              disableLine: true,\n            },\n          ]}\n          yAxis={[\n            {\n              id: \"actual\",\n              position: \"left\",\n              width: 140,\n              scaleType: \"band\",\n              data: classes,\n              categoryGapRatio: 0.08,\n              label: TRUE_LABELS,\n              labelStyle: { fontSize: 18, fill: tokens.ink, fontFamily: \"inherit\" },\n              tickLabelStyle: { fontSize: 16, fill: tokens.inkSoft, fontFamily: \"inherit\" },\n              disableTicks: true,\n              disableLine: true,\n            },\n          ]}\n          zAxis={[\n            {\n              id: \"count\",\n              min: 0,\n              max: maxCount,\n              colorMap: { type: \"continuous\", min: 0, max: maxCount, color: sequentialColor },\n            },\n          ]}\n          margin={{ top: 20, right: 20, bottom: 24, left: 60 }}\n          slots={{ scatter: ConfusionCell, legend: CountLegend }}\n          slotProps={{\n            legend: {\n              axisId: \"count\",\n              axisDirection: \"z\",\n              direction: \"horizontal\",\n              position: { vertical: \"bottom\", horizontal: \"end\" },\n              thickness: 14,\n              sx: {\n                color: tokens.inkSoft,\n                fontSize: 16,\n                fontFamily: \"inherit\",\n              },\n            } as any,\n          }}\n        />\n      </Box>\n    </Box>\n  );\n}\n"}