{"spec_id":"area-stacked-percent","library":"muix","language":"javascript","code":"// anyplot.ai\n// area-stacked-percent: 100% Stacked Area Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 89/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { useDrawingArea, useXScale } 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 = \"area-stacked-percent · javascript · muix · anyplot.ai\";\nconst TITLE_H = 84;\nconst LEGEND_H = 44;\nconst Y_LABEL = \"Share of total (%)\";\nconst MAJORITY = 0.5; // a share below this ends a category's majority of the total\n\n// Columns: set these to your data's column names\nconst YEAR = \"Year\"; // role: time\nconst SOURCE = \"Source\"; // role: category\nconst GENERATION = \"Generation (TWh)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Illustrative electricity generation mix, 2010 to 2024: solar and wind grow\n// quadratically along a falling cost curve, hydro and nuclear stay roughly flat,\n// fossil declines linearly\nconst data = Array.from({ length: 15 }, (_, i) => [\n  { [YEAR]: 2010 + i, [SOURCE]: \"Solar\", [GENERATION]: 4 + Math.round(i * i * 1.6) },\n  { [YEAR]: 2010 + i, [SOURCE]: \"Wind\", [GENERATION]: 15 + Math.round(i * i * 0.9) },\n  { [YEAR]: 2010 + i, [SOURCE]: \"Hydro\", [GENERATION]: 150 + i * 3 },\n  { [YEAR]: 2010 + i, [SOURCE]: \"Nuclear\", [GENERATION]: 260 - i * 2 },\n  { [YEAR]: 2010 + i, [SOURCE]: \"Fossil\", [GENERATION]: 680 - i * 18 },\n]).flat();\n\n// Plot: reads only data and the constants above\nconst years = [...new Set(data.map((d) => d[YEAR]))].sort((a, b) => a - b);\nconst sources = [...new Set(data.map((d) => d[SOURCE]))];\nconst valueByKey = new Map(data.map((d) => [`${d[SOURCE]}|${d[YEAR]}`, d[GENERATION]]));\nconst values = sources.map((s) => years.map((y) => valueByKey.get(`${s}|${y}`) ?? null));\nconst totals = years.map((_, k) => values.reduce((sum, row) => sum + (row[k] ?? 0), 0));\nconst shares = values.map((row) => row.map((v, k) => (v == null || !totals[k] ? null : v / totals[k])));\nconst UNIT = GENERATION.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\n\n// Focal point: the first year in which the category leading the first year loses\n// its majority, drawn only when it starts with a majority and later loses it\nconst leader = shares.reduce((best, row, g) => ((row[0] ?? 0) > (shares[best][0] ?? 0) ? g : best), 0);\nconst lossIdx = (shares[leader][0] ?? 0) >= MAJORITY ? shares[leader].findIndex((v) => v != null && v < MAJORITY) : -1;\nconst milestone =\n  lossIdx > 0\n    ? { year: years[lossIdx], text: `${years[lossIdx]}: ${sources[leader]} falls below ${Math.round(MAJORITY * 100)}% of the total` }\n    : null;\n\nconst SUBTITLE = `${years.length} years, ${years[0]}–${years[years.length - 1]} · ${sources.length} categories · each year's total = 100%`;\n\n// Dashed marker at the milestone year, labelled above the drawing area on the page\nfunction MilestoneMarker() {\n  const xScale = useXScale();\n  const { top, height } = useDrawingArea();\n  if (!milestone) return null;\n  const x = xScale(milestone.year);\n  return (\n    <g>\n      <line x1={x} x2={x} y1={top - 6} y2={top + height} stroke={t.ink} strokeWidth={1.75} strokeDasharray=\"6 4\" />\n      <text x={x} y={top - 14} textAnchor=\"middle\" fontSize={15} fontWeight={600} fill={t.ink}>\n        {milestone.text}\n      </text>\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      <LineChart\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        skipAnimation\n        grid={{ horizontal: true }}\n        xAxis={[\n          {\n            data: years,\n            scaleType: \"point\",\n            label: YEAR,\n            valueFormatter: (v: number) => `${v}`,\n            height: 64,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            max: 1,\n            label: Y_LABEL,\n            width: 76,\n            valueFormatter: (v: number) => `${Math.round(v * 100)}%`,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={sources.map((source, g) => ({\n          id: `source-${g}`,\n          label: source,\n          data: values[g],\n          color: t.palette[g],\n          stack: \"total\",\n          stackOffset: \"expand\" as const,\n          area: true,\n          showMark: false,\n          labelMarkType: \"square\" as const,\n          valueFormatter: (v: number | null, { dataIndex }: { dataIndex: number }) =>\n            v == null ? \"\" : `${Math.round((shares[g][dataIndex] ?? 0) * 100)}% · ${v.toLocaleString(\"en-US\")} ${UNIT}`.trim(),\n        }))}\n        margin={{ top: 40, right: 48, bottom: 8, left: 24 }}\n        slotProps={{\n          legend: {\n            position: { vertical: \"bottom\", horizontal: \"center\" },\n            sx: { fontSize: 15, color: t.ink },\n          },\n        }}\n        sx={{\n          \"& .MuiLineChart-area\": { fillOpacity: 0.9, filter: \"none\" },\n          \"& .MuiLineChart-line\": { strokeWidth: 2 },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      >\n        <MilestoneMarker />\n      </LineChart>\n    </Box>\n  );\n}\n"}