{"spec_id":"area-stacked-confidence","library":"muix","language":"javascript","code":"// anyplot.ai\n// area-stacked-confidence: Stacked Area Chart with Confidence Bands\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"area-stacked-confidence · javascript · muix · anyplot.ai\";\nconst TITLE_H = 84;\nconst LEGEND_H = 44;\nconst BAND_OPACITY = 0.32;\nconst SYMMETRY_TOL = 0.05; // bounds whose offsets differ by less than this share of the band width count as symmetric\n\n// Columns: set these to your data's column names\nconst QUARTER = \"Quarter\"; // role: x\nconst PRODUCT_LINE = \"Product line\"; // role: category\nconst REVENUE = \"Revenue ($M)\"; // role: y\nconst LOWER = \"Lower bound ($M)\"; // role: y_lower\nconst UPPER = \"Upper bound ($M)\"; // role: y_upper\nconst BAND_NAME = \"90% prediction interval\"; // what the lower and upper bounds describe\n\n// Data: replace this block with your own records, one object per row\n// Quarterly revenue forecast by product line, Q1 2024 to Q4 2028, largest line\n// first so it anchors the stack. The interval widens with the forecast horizon,\n// the fan-out of a real forecast. Seeded LCG, since the browser has no seeded RNG.\nconst data = (() => {\n  let state = 42;\n  const random = () => {\n    state = (state * 1103515245 + 12345) % 2147483648;\n    return state / 2147483648;\n  };\n  const lines = [\n    { name: \"Hardware\", base: 42, trend: -0.35, season: 3.0, phase: 0, spread: 0.04, growth: 0.006 },\n    { name: \"Software\", base: 18, trend: 1.15, season: 1.6, phase: 1.4, spread: 0.05, growth: 0.009 },\n    { name: \"Services\", base: 10, trend: 0.55, season: 0.9, phase: 2.6, spread: 0.045, growth: 0.007 },\n  ];\n  return lines.flatMap((line) =>\n    Array.from({ length: 20 }, (_, i) => {\n      const center = Math.max(\n        1,\n        line.base + line.trend * i + line.season * Math.sin((i * Math.PI) / 2 + line.phase) + (random() - 0.5) * 1.6,\n      );\n      const fraction = line.spread + i * line.growth;\n      return {\n        [QUARTER]: new Date(2024 + Math.floor(i / 4), (i % 4) * 3, 1),\n        [PRODUCT_LINE]: line.name,\n        [REVENUE]: Number(center.toFixed(2)),\n        [LOWER]: Number((center * (1 - fraction)).toFixed(2)),\n        [UPPER]: Number((center * (1 + fraction)).toFixed(2)),\n      };\n    }),\n  );\n})();\n\n// Plot: reads only data and the constants above\nconst quarters = [...new Map(data.map((d) => [d[QUARTER].getTime(), d[QUARTER]])).values()].sort(\n  (a, b) => a.getTime() - b.getTime(),\n);\nconst lines = [...new Set(data.map((d) => d[PRODUCT_LINE]))];\nconst rowByKey = new Map(data.map((d) => [`${d[PRODUCT_LINE]}|${d[QUARTER].getTime()}`, d]));\nconst cells = lines.map((line) => quarters.map((q) => rowByKey.get(`${line}|${q.getTime()}`) ?? null));\n\n// Stack offset below each layer, shared by its central area and its band so both\n// keep one stack order at every quarter\nconst below = lines.map((_, g) =>\n  quarters.map((_, k) => cells.slice(0, g).reduce((s, row) => s + (row[k]?.[REVENUE] ?? 0), 0)),\n);\n\n// Band half-widths relative to the central value, for the symmetry note and subtitle\nconst halfShares = data.map((d) => (d[UPPER] - d[LOWER]) / 2 / d[REVENUE]);\nconst asymmetry = Math.max(\n  ...data.map((d) => Math.abs(d[UPPER] - d[REVENUE] - (d[REVENUE] - d[LOWER])) / (d[UPPER] - d[LOWER] || 1)),\n);\nconst symmetric = asymmetry <= SYMMETRY_TOL;\nconst fmtQuarter = (v: Date) => `Q${Math.floor(v.getMonth() / 3) + 1} ${v.getFullYear()}`;\n\nconst SUBTITLE = `${quarters.length} quarters, ${fmtQuarter(quarters[0])} – ${fmtQuarter(quarters[quarters.length - 1])} · ${lines.length} stacked series · band half-width ${Math.round(Math.min(...halfShares) * 100)}–${Math.round(Math.max(...halfShares) * 100)}% of the value`;\nconst BAND_LEGEND = `${BAND_NAME} around each layer's edge${symmetric ? \"\" : \" (asymmetric)\"}`;\n\n// Each band is two stacked series: an invisible one carrying the offset (stack\n// below + lower bound) and a filled one adding the band's own width on top\nconst series = [\n  ...lines.map((line, g) => ({\n    id: `line-${g}`,\n    label: line,\n    data: cells[g].map((d) => d?.[REVENUE] ?? null),\n    color: t.palette[g],\n    stack: \"revenue\",\n    area: true,\n    showMark: false,\n    curve: \"monotoneX\" as const,\n    // The tooltip row carries the bounds, since the band helpers below stay out of it\n    valueFormatter: (v: number | null, { dataIndex }: { dataIndex: number }) => {\n      const d = cells[g][dataIndex];\n      return v == null || !d ? null : `$${v.toFixed(1)}M (${d[LOWER].toFixed(1)}–${d[UPPER].toFixed(1)})`;\n    },\n  })),\n  ...lines.flatMap((_, g) => [\n    {\n      id: `band-base-${g}`,\n      data: cells[g].map((d, k) => (d ? below[g][k] + d[LOWER] : null)),\n      color: t.palette[g],\n      stack: `band-${g}`,\n      showMark: false,\n      curve: \"monotoneX\" as const,\n      valueFormatter: () => null,\n    },\n    {\n      id: `band-width-${g}`,\n      data: cells[g].map((d) => (d ? d[UPPER] - d[LOWER] : null)),\n      color: t.palette[g],\n      stack: `band-${g}`,\n      area: true,\n      showMark: false,\n      curve: \"monotoneX\" as const,\n      valueFormatter: () => null,\n    },\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      <LineChart\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        skipAnimation\n        hideLegend\n        grid={{ horizontal: true }}\n        xAxis={[\n          {\n            data: quarters,\n            scaleType: \"time\",\n            valueFormatter: fmtQuarter,\n            tickInterval: quarters.filter((_, k) => k % 2 === 0), // every other quarter keeps labels apart\n            label: QUARTER,\n            height: 64,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            label: REVENUE,\n            width: 76,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={series}\n        margin={{ top: 12, right: 40, bottom: 8, left: 24 }}\n        sx={{\n          '& .MuiLineChart-area[data-series^=\"line-\"]': { fillOpacity: 0.85, filter: \"none\" },\n          '& .MuiLineChart-line[data-series^=\"line-\"]': { strokeWidth: 2.5 },\n          '& .MuiLineChart-area[data-series^=\"band-width-\"]': { fillOpacity: BAND_OPACITY, filter: \"none\" },\n          '& .MuiLineChart-line[data-series^=\"band-\"]': { display: \"none\" },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      />\n      <Box\n        sx={{\n          height: LEGEND_H,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: \"28px\",\n          pb: \"8px\",\n          boxSizing: \"border-box\",\n        }}\n      >\n        {lines.map((line, g) => (\n          <Box key={line} sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n            <Box sx={{ width: 16, height: 16, bgcolor: t.palette[g], borderRadius: \"3px\" }} />\n            <Typography sx={{ fontSize: 15, color: t.ink }}>{line}</Typography>\n          </Box>\n        ))}\n        <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n          <Box\n            sx={{\n              width: 28,\n              height: 16,\n              borderRadius: \"3px\",\n              background: `linear-gradient(90deg, ${lines.map((_, g) => t.palette[g]).join(\", \")})`,\n              opacity: BAND_OPACITY + 0.2,\n            }}\n          />\n          <Typography sx={{ fontSize: 15, color: t.ink }}>{BAND_LEGEND}</Typography>\n        </Box>\n      </Box>\n    </Box>\n  );\n}\n"}