{"spec_id":"mosaic-categorical","library":"muix","language":"javascript","code":"// anyplot.ai\n// mosaic-categorical: Mosaic Plot for Categorical Association Analysis\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst OUTCOME_SLOT = { Survived: 0, \"Did not survive\": 4 }; // semantic palette slots: survival green, death matte red\nconst GAP_X = 0.018; // share of the full width left open between neighbouring columns\nconst GAP_Y = 2; // percentage points left open between stacked tiles\nconst TITLE_H = 48;\nconst SUBTITLE_H = 28;\nconst LEGEND_H = 48;\nconst Y_AXIS_W = 84;\nconst MARGIN = { top: 12, right: 48, bottom: 112, left: 24 };\n\n// Columns: set these to your data's column names\nconst CLASS = \"Passenger class\"; // role: category_1\nconst OUTCOME = \"Outcome\"; // role: category_2\nconst PASSENGERS = \"Passengers\"; // role: frequency\n\n// Data: replace this block with your own records, one object per row\n// Titanic passengers by cabin class and survival (crew excluded)\nconst data = [\n  { [CLASS]: \"1st Class\", [OUTCOME]: \"Survived\", [PASSENGERS]: 203 },\n  { [CLASS]: \"1st Class\", [OUTCOME]: \"Did not survive\", [PASSENGERS]: 122 },\n  { [CLASS]: \"2nd Class\", [OUTCOME]: \"Survived\", [PASSENGERS]: 118 },\n  { [CLASS]: \"2nd Class\", [OUTCOME]: \"Did not survive\", [PASSENGERS]: 167 },\n  { [CLASS]: \"3rd Class\", [OUTCOME]: \"Survived\", [PASSENGERS]: 178 },\n  { [CLASS]: \"3rd Class\", [OUTCOME]: \"Did not survive\", [PASSENGERS]: 528 },\n];\n\n// Plot: reads only data and the constants above\nconst classes = [...new Set(data.map((d) => d[CLASS]))];\nconst outcomes = [...new Set(data.map((d) => d[OUTCOME]))];\n\n// Semantic slots first; every other outcome takes the unused palette positions in order\nconst freeSlots = t.palette.map((_, i) => i).filter((i) => !outcomes.some((o) => OUTCOME_SLOT[o] === i));\nconst outcomeColor = new Map();\nlet nextFree = 0;\nfor (const outcome of outcomes) {\n  if (outcome in OUTCOME_SLOT) {\n    outcomeColor.set(outcome, t.palette[OUTCOME_SLOT[outcome]]);\n  } else {\n    outcomeColor.set(outcome, t.palette[freeSlots[nextFree]]);\n    nextFree += 1;\n  }\n}\n\n// Contingency table; a row without a frequency counts once (raw observations, as the spec allows)\nconst counts = new Map(classes.map((c) => [c, new Map(outcomes.map((o) => [o, 0]))]));\nfor (const d of data) {\n  const row = counts.get(d[CLASS]);\n  row.set(d[OUTCOME], row.get(d[OUTCOME]) + (d[PASSENGERS] ?? 1));\n}\nconst classTotals = classes.map((c) => [...counts.get(c).values()].reduce((a, b) => a + b, 0));\nconst outcomeTotals = outcomes.map((o) => classes.reduce((sum, c) => sum + counts.get(c).get(o), 0));\nconst grandTotal = classTotals.reduce((a, b) => a + b, 0);\n\n// Pearson chi-square test of independence\nlet chiSquare = 0;\nclasses.forEach((c, i) => {\n  outcomes.forEach((o, j) => {\n    const expected = (classTotals[i] * outcomeTotals[j]) / grandTotal;\n    if (expected > 0) chiSquare += (counts.get(c).get(o) - expected) ** 2 / expected;\n  });\n});\nconst degreesOfFreedom = (classes.length - 1) * (outcomes.length - 1);\n\n// Mosaic layout: column width = marginal share of the class (x in 0..1),\n// tile height = conditional share of the outcome within the class (y in 0..100 %). The gaps\n// between stacked tiles come out of the column first and the shares are scaled into what is\n// left, so every tile keeps its proportion and no small share collapses to nothing\nlet cursor = 0;\nconst columns = classes.map((c, i) => {\n  const x0 = cursor;\n  cursor += classTotals[i] / grandTotal;\n  const drawn = outcomes.filter((o) => counts.get(c).get(o) > 0);\n  const usable = 100 - (drawn.length - 1) * GAP_Y;\n  let level = 0;\n  const tiles = drawn.map((o, k) => {\n    const y0 = level + (k > 0 ? GAP_Y : 0);\n    level = y0 + (counts.get(c).get(o) / classTotals[i]) * usable;\n    return { outcome: o, y0, y1: level };\n  });\n  return { label: c, total: classTotals[i], x0, x1: cursor, tiles };\n});\n\nconst TITLE = \"Titanic Survival by Class · mosaic-categorical · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${PASSENGERS}: ${grandTotal.toLocaleString(\"en-US\")} · ${classes.length} × ${outcomes.length} table · Pearson χ² = ${chiSquare.toFixed(1)}, df = ${degreesOfFreedom}`;\n\nfunction MosaicTiles() {\n  const xScale = useXScale(\"x\");\n  const yScale = useYScale(\"y\");\n  const { left, top, width, height } = useDrawingArea();\n  const bottom = top + height;\n\n  return (\n    <g>\n      {columns.map((col) => {\n        const px0 = xScale(col.x0 + GAP_X / 2);\n        const px1 = xScale(col.x1 - GAP_X / 2);\n        const mid = (px0 + px1) / 2;\n        return (\n          <g key={col.label}>\n            {col.tiles.map((tile) => (\n              <rect\n                key={tile.outcome}\n                x={px0}\n                y={yScale(tile.y1)}\n                width={Math.max(0, px1 - px0)}\n                height={yScale(tile.y0) - yScale(tile.y1)}\n                fill={outcomeColor.get(tile.outcome)}\n              />\n            ))}\n            <text x={mid} y={bottom + 28} textAnchor=\"middle\" fontSize={16} fontWeight={600} fill={t.ink}>\n              {col.label}\n            </text>\n            <text x={mid} y={bottom + 52} textAnchor=\"middle\" fontSize={14} fill={t.inkSoft}>\n              n = {col.total.toLocaleString(\"en-US\")} ({((col.total / grandTotal) * 100).toFixed(1)}%)\n            </text>\n          </g>\n        );\n      })}\n      <text x={left + width / 2} y={bottom + 92} textAnchor=\"middle\" fontSize={16} fill={t.ink}>\n        {CLASS} (column width ∝ {PASSENGERS})\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: TITLE_H, display: \"flex\", alignItems: \"flex-end\", justifyContent: \"center\", fontSize: 22, fontWeight: 600, color: t.ink }}>\n        {TITLE}\n      </div>\n      <div style={{ height: SUBTITLE_H, display: \"flex\", alignItems: \"center\", justifyContent: \"center\", fontSize: 15, color: t.inkSoft }}>\n        {SUBTITLE}\n      </div>\n      <div style={{ height: LEGEND_H, display: \"flex\", alignItems: \"center\", justifyContent: \"center\", gap: 24, fontSize: 15 }}>\n        <span style={{ color: t.ink, fontWeight: 600 }}>{OUTCOME}</span>\n        {outcomes.map((o) => (\n          <span key={o} style={{ display: \"flex\", alignItems: \"center\", gap: 8, color: t.inkSoft }}>\n            <span style={{ width: 16, height: 16, borderRadius: 3, backgroundColor: outcomeColor.get(o) }} />\n            {o}\n          </span>\n        ))}\n      </div>\n      <ChartsContainer\n        width={width}\n        height={height - TITLE_H - SUBTITLE_H - LEGEND_H}\n        margin={MARGIN}\n        series={[]}\n        xAxis={[{ id: \"x\", scaleType: \"linear\", min: 0, max: 1, position: \"none\" }]}\n        yAxis={[\n          {\n            id: \"y\",\n            scaleType: \"linear\",\n            min: 0,\n            max: 100,\n            width: Y_AXIS_W,\n            label: `${OUTCOME} within ${CLASS} (%)`,\n            valueFormatter: (v) => `${v}%`,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n        }}\n        skipAnimation\n      >\n        <MosaicTiles />\n        <ChartsYAxis axisId=\"y\" />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}