{"spec_id":"bar-spine","library":"muix","language":"javascript","code":"// anyplot.ai\n// bar-spine: Spine Plot for Two-Variable Proportions\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 { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"Customer Churn by Subscription Tier · bar-spine · javascript · muix · anyplot.ai\";\nconst TITLE_H = 84;\nconst LEGEND_H = 40;\nconst FULL = 100; // every spine bar spans the whole, 0 to 100 %\nconst Y_TICKS = [0, 0.25, 0.5, 0.75, 1].map((f) => f * FULL);\nconst DECIMALS = 1;\nconst MIN_LABEL_W = 64; // px; a narrower segment keeps no percentage label\nconst MIN_LABEL_H = 24; // px; a shorter segment keeps no percentage label\n// Outcome semantics: retained is good (green), downgraded a warning (amber), churned bad (red);\n// an outcome outside the map takes the unused palette positions in order\nconst OUTCOME_COLORS = new Map([\n  [\"Retained\", t.palette[0]],\n  [\"Downgraded\", t.amber],\n  [\"Churned\", t.palette[4]],\n]);\n// Fixed label inks: segment fills keep their hex in both themes, so the ink follows the fill\nconst DARK_INK = \"#1A1A17\";\nconst LIGHT_INK = \"#FAF8F1\";\n\n// Columns: set these to your data's column names\nconst TIER = \"Subscription tier\"; // role: x_category\nconst OUTCOME = \"Outcome\"; // role: fill_category\nconst CUSTOMERS = \"Customers\"; // role: count\n\n// Data: replace this block with your own records, one object per row\n// Customers per subscription tier, split by what they did at renewal\nconst data = [\n  { [TIER]: \"Free\", [OUTCOME]: \"Retained\", [CUSTOMERS]: 2636 },\n  { [TIER]: \"Free\", [OUTCOME]: \"Downgraded\", [CUSTOMERS]: 900 },\n  { [TIER]: \"Free\", [OUTCOME]: \"Churned\", [CUSTOMERS]: 1664 },\n  { [TIER]: \"Basic\", [OUTCOME]: \"Retained\", [CUSTOMERS]: 1949 },\n  { [TIER]: \"Basic\", [OUTCOME]: \"Downgraded\", [CUSTOMERS]: 500 },\n  { [TIER]: \"Basic\", [OUTCOME]: \"Churned\", [CUSTOMERS]: 651 },\n  { [TIER]: \"Pro\", [OUTCOME]: \"Retained\", [CUSTOMERS]: 1404 },\n  { [TIER]: \"Pro\", [OUTCOME]: \"Downgraded\", [CUSTOMERS]: 180 },\n  { [TIER]: \"Pro\", [OUTCOME]: \"Churned\", [CUSTOMERS]: 216 },\n  { [TIER]: \"Enterprise\", [OUTCOME]: \"Retained\", [CUSTOMERS]: 638 },\n  { [TIER]: \"Enterprise\", [OUTCOME]: \"Downgraded\", [CUSTOMERS]: 20 },\n  { [TIER]: \"Enterprise\", [OUTCOME]: \"Churned\", [CUSTOMERS]: 42 },\n];\n\n// Plot: reads only data and the constants above\n// Tiers left to right and outcomes bottom to top, both in order of first appearance\nconst tiers = [...new Set(data.map((d) => d[TIER]))];\nconst outcomes = [...new Set(data.map((d) => d[OUTCOME]))];\nconst rows = data.filter((d) => d[CUSTOMERS] != null);\nconst tierTotals = tiers.map((tier) => rows.filter((d) => d[TIER] === tier).reduce((a, d) => a + d[CUSTOMERS], 0));\nconst grandTotal = tierTotals.reduce((a, v) => a + v, 0);\n\n// Bar edges on the count axis: each tier is as wide as its marginal count\nconst tierStarts = tierTotals.map((_, i) => tierTotals.slice(0, i).reduce((a, v) => a + v, 0));\nconst tierCenters = tierStarts.map((x0, i) => x0 + tierTotals[i] / 2);\nconst tickLabels = new Map(\n  tierCenters.map((c, i) => [c, `${tiers[i]}\\n${tierTotals[i].toLocaleString(\"en-US\")}`]),\n);\n\nconst spare = t.palette.filter((c) => ![...OUTCOME_COLORS.values()].includes(c));\nconst unmatched = outcomes.filter((o) => !OUTCOME_COLORS.has(o));\nconst outcomeColors = outcomes.map((o) => OUTCOME_COLORS.get(o) ?? spare[unmatched.indexOf(o)]);\n// Label ink per outcome: whichever fixed ink contrasts more with the outcome's fill\nconst outcomeInks = outcomeColors.map((hex) => {\n  const [R, G, B] = [1, 3, 5].map((k) => {\n    const c = parseInt(hex.slice(k, k + 2), 16) / 255;\n    return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n  });\n  const lum = 0.2126 * R + 0.7152 * G + 0.0722 * B;\n  return (lum + 0.05) / 0.0603 >= 0.985 / (lum + 0.05) ? DARK_INK : LIGHT_INK;\n});\n\n// Segments: conditional share of each outcome within its tier, stacked from zero to FULL\nconst segments = tiers.flatMap((tier, ti) => {\n  let base = 0;\n  return outcomes.flatMap((outcome, oi) => {\n    const row = rows.find((d) => d[TIER] === tier && d[OUTCOME] === outcome);\n    if (!row || !tierTotals[ti]) return [];\n    const share = (row[CUSTOMERS] / tierTotals[ti]) * FULL;\n    const seg = {\n      key: `${ti}-${oi}`,\n      x0: tierStarts[ti],\n      x1: tierStarts[ti] + tierTotals[ti],\n      y0: base,\n      y1: base + share,\n      fill: outcomeColors[oi],\n      ink: outcomeInks[oi],\n      label: `${share.toFixed(DECIMALS)}%`,\n    };\n    base += share;\n    return [seg];\n  });\n});\n\nconst SUBTITLE = `Bar width ∝ ${CUSTOMERS.toLowerCase()} per ${TIER.toLowerCase()} (n = ${grandTotal.toLocaleString(\"en-US\")}) · segment height = ${OUTCOME.toLowerCase()} share within the bar`;\n\n// Custom layer: the variable-width stacked bars, drawn in data coordinates\nfunction SpineSegments() {\n  const xScale = useXScale(\"count\");\n  const yScale = useYScale(\"share\");\n\n  return (\n    <g>\n      {segments.map((s) => {\n        const x = xScale(s.x0);\n        const w = xScale(s.x1) - x;\n        const y = yScale(s.y1);\n        const h = yScale(s.y0) - y;\n        return (\n          <g key={s.key}>\n            <rect x={x} y={y} width={w} height={h} fill={s.fill} stroke={t.elevatedBg} strokeWidth={1} />\n            {w >= MIN_LABEL_W && h >= MIN_LABEL_H && (\n              <text\n                x={x + w / 2}\n                y={y + h / 2}\n                textAnchor=\"middle\"\n                dominantBaseline=\"central\"\n                fill={s.ink}\n                fontSize={15}\n                fontWeight={600}\n              >\n                {s.label}\n              </text>\n            )}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <Box sx={{ height: TITLE_H, px: \"40px\", pt: \"18px\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ color: t.ink, fontSize: \"22px\", fontWeight: 600, lineHeight: 1.2 }}>\n          {TITLE}\n        </Typography>\n        <Typography sx={{ color: t.inkSoft, fontSize: \"15px\", lineHeight: 1.2, mt: \"8px\" }}>\n          {SUBTITLE}\n        </Typography>\n      </Box>\n      <Box sx={{ height: LEGEND_H, display: \"flex\", alignItems: \"center\", justifyContent: \"center\", gap: \"28px\" }}>\n        {outcomes.map((outcome, i) => (\n          <Box key={outcome} sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n            <Box sx={{ width: 16, height: 16, borderRadius: \"3px\", bgcolor: outcomeColors[i] }} />\n            <Typography sx={{ fontSize: 15, color: t.ink }}>{outcome}</Typography>\n          </Box>\n        ))}\n      </Box>\n      <ChartsContainer\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        skipAnimation\n        series={[]}\n        xAxis={[\n          {\n            id: \"count\",\n            scaleType: \"linear\",\n            min: 0,\n            max: grandTotal,\n            label: TIER,\n            height: 84,\n            // One tick under the centre of each bar, named by its tier and its count\n            tickInterval: tierCenters,\n            valueFormatter: (v: number) => tickLabels.get(v) ?? \"\",\n            disableTicks: true,\n            tickLabelStyle: { fontSize: 15, fill: t.ink },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"share\",\n            scaleType: \"linear\",\n            min: 0,\n            max: FULL,\n            tickInterval: Y_TICKS,\n            label: `Share of ${CUSTOMERS.toLowerCase()} (%)`,\n            width: 72,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        margin={{ top: 12, right: 48, bottom: 8, left: 24 }}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n        }}\n      >\n        <SpineSegments />\n        <ChartsXAxis axisId=\"count\" />\n        <ChartsYAxis axisId=\"share\" />\n      </ChartsContainer>\n    </Box>\n  );\n}\n"}