{"spec_id":"parallel-categories-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// parallel-categories-basic: Basic Parallel Categories Plot\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 83/100 | Updated: 2026-10-24\n\nimport { useState } from \"react\";\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"parallel-categories-basic · javascript · muix · anyplot.ai\";\nconst TITLE_FONT_SIZE = 22;\nconst HEADER_H = 118;\nconst PAD = 40;\nconst GAP = 34;\nconst NODE_HALF = 13;\nconst OUTCOME_SEMANTICS: Record<string, { color: string; hatched: boolean }> = {\n  Survived: { color: t.palette[0], hatched: false },\n  \"Did not survive\": { color: t.palette[4], hatched: true },\n};\nconst UNUSED_PALETTE = [t.palette[1], t.palette[2], t.palette[3], t.palette[5]];\nconst HATCH_OPACITY = 0.45;\nconst hatchInk = `color-mix(in srgb, ${t.ink} ${HATCH_OPACITY * 100}%, transparent)`;\n\n// Columns: set these to your data's column names\nconst DIMENSIONS = [\"Passenger class\", \"Sex\", \"Outcome\"]; // role: dimension\nconst COUNT = \"Passengers\"; // role: value\n\n// Data: replace this block with your own records\nconst data: Array<Record<string, string | number>> = [\n  { [DIMENSIONS[0]]: \"1st\", [DIMENSIONS[1]]: \"Female\", [DIMENSIONS[2]]: \"Survived\", [COUNT]: 91 },\n  { [DIMENSIONS[0]]: \"1st\", [DIMENSIONS[1]]: \"Female\", [DIMENSIONS[2]]: \"Did not survive\", [COUNT]: 3 },\n  { [DIMENSIONS[0]]: \"1st\", [DIMENSIONS[1]]: \"Male\", [DIMENSIONS[2]]: \"Survived\", [COUNT]: 45 },\n  { [DIMENSIONS[0]]: \"1st\", [DIMENSIONS[1]]: \"Male\", [DIMENSIONS[2]]: \"Did not survive\", [COUNT]: 77 },\n  { [DIMENSIONS[0]]: \"2nd\", [DIMENSIONS[1]]: \"Female\", [DIMENSIONS[2]]: \"Survived\", [COUNT]: 70 },\n  { [DIMENSIONS[0]]: \"2nd\", [DIMENSIONS[1]]: \"Female\", [DIMENSIONS[2]]: \"Did not survive\", [COUNT]: 6 },\n  { [DIMENSIONS[0]]: \"2nd\", [DIMENSIONS[1]]: \"Male\", [DIMENSIONS[2]]: \"Survived\", [COUNT]: 17 },\n  { [DIMENSIONS[0]]: \"2nd\", [DIMENSIONS[1]]: \"Male\", [DIMENSIONS[2]]: \"Did not survive\", [COUNT]: 91 },\n  { [DIMENSIONS[0]]: \"3rd\", [DIMENSIONS[1]]: \"Female\", [DIMENSIONS[2]]: \"Survived\", [COUNT]: 72 },\n  { [DIMENSIONS[0]]: \"3rd\", [DIMENSIONS[1]]: \"Female\", [DIMENSIONS[2]]: \"Did not survive\", [COUNT]: 72 },\n  { [DIMENSIONS[0]]: \"3rd\", [DIMENSIONS[1]]: \"Male\", [DIMENSIONS[2]]: \"Survived\", [COUNT]: 47 },\n  { [DIMENSIONS[0]]: \"3rd\", [DIMENSIONS[1]]: \"Male\", [DIMENSIONS[2]]: \"Did not survive\", [COUNT]: 300 },\n];\n\n// Plot: reads only data and the constants above\nconst totalCount = data.reduce((sum, row) => sum + Number(row[COUNT]), 0);\n\nconst columnDefs = DIMENSIONS.map((col) => {\n  const order: string[] = [];\n  const totals = new Map<string, number>();\n  for (const row of data) {\n    const val = String(row[col]);\n    const cnt = Number(row[COUNT]);\n    if (!order.includes(val)) order.push(val);\n    totals.set(val, (totals.get(val) ?? 0) + cnt);\n  }\n  return { col, order, totals };\n});\n\nconst outcomeDim = DIMENSIONS[DIMENSIONS.length - 1];\nconst outcomeOrder = columnDefs[columnDefs.length - 1].order;\nconst outcomeStyles: Record<string, { color: string; hatched: boolean }> = {};\nlet fallbackIdx = 0;\nfor (const name of outcomeOrder) {\n  if (OUTCOME_SEMANTICS[name]) {\n    outcomeStyles[name] = OUTCOME_SEMANTICS[name];\n  } else {\n    outcomeStyles[name] = {\n      color: UNUSED_PALETTE[fallbackIdx % UNUSED_PALETTE.length],\n      hatched: false,\n    };\n    fallbackIdx += 1;\n  }\n}\n\nconst maxNodes = Math.max(...columnDefs.map((d) => d.order.length));\n\nfunction ParallelCategories() {\n  const area = useDrawingArea();\n  const [hoveredRow, setHoveredRow] = useState<number | null>(null);\n\n  const k = (area.height - GAP * (maxNodes - 1)) / totalCount;\n  const colCount = columnDefs.length;\n  const colX = columnDefs.map((_, ci) => area.left + (ci * area.width) / (colCount - 1));\n\n  const colNodes: Array<Record<string, { y0: number; y1: number; total: number }>> = [];\n  const colSegs: Array<Array<{ y0: number; y1: number }>> = [];\n\n  for (const def of columnDefs) {\n    const heights = new Map<string, number>();\n    for (const row of data) {\n      const name = String(row[def.col]);\n      const h = Number(row[COUNT]) * k;\n      heights.set(name, (heights.get(name) ?? 0) + h);\n    }\n\n    let contentHeight = GAP * (def.order.length - 1);\n    for (const name of def.order) {\n      contentHeight += heights.get(name) ?? 0;\n    }\n\n    let yCursor = area.top + (area.height - contentHeight) / 2;\n    const nodesMap: Record<string, { y0: number; y1: number; total: number }> = {};\n    const segCursor: Record<string, number> = {};\n\n    for (const name of def.order) {\n      const h = heights.get(name) ?? 0;\n      nodesMap[name] = { y0: yCursor, y1: yCursor + h, total: def.totals.get(name) ?? 0 };\n      segCursor[name] = yCursor;\n      yCursor += h + GAP;\n    }\n    colNodes.push(nodesMap);\n\n    const segsForCol: Array<{ y0: number; y1: number }> = [];\n    for (const row of data) {\n      const name = String(row[def.col]);\n      const y0 = segCursor[name];\n      const y1 = y0 + Number(row[COUNT]) * k;\n      segCursor[name] = y1;\n      segsForCol.push({ y0, y1 });\n    }\n    colSegs.push(segsForCol);\n  }\n\n  return (\n    <g>\n      <defs>\n        <pattern\n          id=\"outcome-hatch\"\n          patternUnits=\"userSpaceOnUse\"\n          width={6}\n          height={6}\n          patternTransform=\"rotate(45)\"\n        >\n          <line x1={0} y1={0} x2={0} y2={6} stroke={t.ink} strokeOpacity={HATCH_OPACITY} strokeWidth={1.5} />\n        </pattern>\n      </defs>\n\n      {columnDefs.map((def, i) => (\n        <text\n          key={def.col}\n          x={colX[i]}\n          y={area.top - 22}\n          textAnchor=\"middle\"\n          fontSize={15}\n          fontWeight={600}\n          fill={t.inkSoft}\n        >\n          {def.col}\n        </text>\n      ))}\n\n      {data.map((row, i) => {\n        const outcome = String(row[outcomeDim]);\n        const style = outcomeStyles[outcome];\n        const isHovered = hoveredRow === i;\n        const isDimmed = hoveredRow !== null && !isHovered;\n        const fillOpacity = isDimmed ? 0.12 : isHovered ? 0.92 : 0.78;\n        const strokeOpacity = isDimmed ? 0.06 : isHovered ? 0.35 : 0.12;\n        const strokeWidth = isHovered ? 1.5 : 1;\n\n        return (\n          <g key={`flow-${i}`}>\n            {Array.from({ length: colCount - 1 }, (_, ci) => {\n              const xStart = colX[ci] + NODE_HALF;\n              const xEnd = colX[ci + 1] - NODE_HALF;\n              const xMid = (xStart + xEnd) / 2;\n              const segA = colSegs[ci][i];\n              const segB = colSegs[ci + 1][i];\n              const d = `M${xStart},${segA.y0} C${xMid},${segA.y0} ${xMid},${segB.y0} ${xEnd},${segB.y0} L${xEnd},${segB.y1} C${xMid},${segB.y1} ${xMid},${segA.y1} ${xStart},${segA.y1} Z`;\n\n              return (\n                <g key={`seg-${ci}`}>\n                  <path\n                    d={d}\n                    fill={style.color}\n                    stroke={t.ink}\n                    cursor=\"pointer\"\n                    fillOpacity={fillOpacity}\n                    strokeOpacity={strokeOpacity}\n                    strokeWidth={strokeWidth}\n                    onMouseEnter={() => setHoveredRow(i)}\n                    onMouseLeave={() => setHoveredRow(null)}\n                  />\n                  {style.hatched && (\n                    <path\n                      d={d}\n                      fill=\"url(#outcome-hatch)\"\n                      fillOpacity={fillOpacity}\n                      pointerEvents=\"none\"\n                    />\n                  )}\n                </g>\n              );\n            })}\n          </g>\n        );\n      })}\n\n      {colNodes.map((nodes, ci) =>\n        Object.entries(nodes).map(([name, node]) => (\n          <rect\n            key={`node-${ci}-${name}`}\n            x={colX[ci] - NODE_HALF}\n            y={node.y0}\n            width={NODE_HALF * 2}\n            height={node.y1 - node.y0}\n            rx={2}\n            fill={t.ink}\n            fillOpacity={0.88}\n          />\n        )),\n      )}\n\n      {colNodes.map((nodes, ci) => {\n        const isFirst = ci === 0;\n        const isLast = ci === colCount - 1;\n        const xPos = isFirst\n          ? colX[ci] - NODE_HALF - 12\n          : isLast\n            ? colX[ci] + NODE_HALF + 12\n            : colX[ci];\n        const textAnchor = isFirst ? \"end\" : isLast ? \"start\" : \"middle\";\n        return Object.entries(nodes).map(([name, node]) => {\n          const yPos = isFirst || isLast ? (node.y0 + node.y1) / 2 : node.y0 - 12;\n          return (\n            <text\n              key={`label-${ci}-${name}`}\n              x={xPos}\n              y={yPos}\n              textAnchor={textAnchor}\n              dominantBaseline={isFirst || isLast ? \"middle\" : \"auto\"}\n              fontSize={14}\n              fill={t.ink}\n            >\n              {`${name} · ${node.total}`}\n            </text>\n          );\n        });\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div\n      style={{\n        width,\n        height,\n        backgroundColor: t.pageBg,\n        position: \"relative\",\n        fontFamily: '\"Helvetica Neue\", Arial, sans-serif',\n        boxSizing: \"border-box\",\n      }}\n    >\n      <div style={{ position: \"absolute\", top: 26, left: PAD, right: PAD }}>\n        <div style={{ color: t.ink, fontSize: TITLE_FONT_SIZE, fontWeight: 600 }}>{TITLE}</div>\n        <div style={{ color: t.inkSoft, fontSize: 15, marginTop: 6 }}>\n          {`${DIMENSIONS.join(\" → \")} across ${totalCount} (${COUNT}) — ribbon width is proportional to ${COUNT}.`}\n        </div>\n        <div style={{ display: \"flex\", gap: 24, marginTop: 12, alignItems: \"center\" }}>\n          {outcomeOrder.map((name) => {\n            const style = outcomeStyles[name];\n            return (\n              <div key={name} style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n                <span\n                  style={{\n                    width: 14,\n                    height: 14,\n                    borderRadius: 3,\n                    backgroundColor: style.color,\n                    backgroundImage: style.hatched\n                      ? `repeating-linear-gradient(45deg, transparent, transparent 2px, ${hatchInk} 2px, ${hatchInk} 3px)`\n                      : undefined,\n                    display: \"inline-block\",\n                  }}\n                />\n                <span style={{ color: t.inkSoft, fontSize: 14 }}>{name}</span>\n              </div>\n            );\n          })}\n        </div>\n      </div>\n      <div style={{ position: \"absolute\", top: HEADER_H, left: PAD }}>\n        <ChartsContainer\n          width={width - PAD * 2}\n          height={height - HEADER_H - PAD / 2}\n          series={[]}\n          xAxis={[{ scaleType: \"linear\", min: 0, max: 1, position: \"none\" }]}\n          yAxis={[{ scaleType: \"linear\", min: 0, max: 1, position: \"none\" }]}\n          margin={{ top: 46, bottom: 12, left: 120, right: 170 }}\n          skipAnimation\n        >\n          <ParallelCategories />\n        </ChartsContainer>\n      </div>\n    </div>\n  );\n}\n"}