{"spec_id":"bar-stacked-percent","library":"muix","language":"javascript","code":"// anyplot.ai\n// bar-stacked-percent: 100% Stacked Bar Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 90/100 | Updated: 2026-11-08\nimport { BarChart } from \"@mui/x-charts/BarChart\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"Electricity Generation Mix · bar-stacked-percent · javascript · muix · anyplot.ai\";\nconst TITLE_H = 84;\nconst LEGEND_H = 44;\nconst FULL = 100; // every bar spans the whole, 0 to 100 %\nconst MIN_LABEL_PX = 30; // a segment shorter than this keeps no percentage label\nconst DECIMALS = 1;\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 COUNTRY = \"Country\"; // role: category\nconst SOURCE = \"Energy source\"; // role: component\nconst GENERATION = \"Electricity generation (TWh per year)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Illustrative annual generation for six national grids of very different size\nconst data = [\n  { [COUNTRY]: \"China\", [SOURCE]: \"Renewables\", [GENERATION]: 3100 },\n  { [COUNTRY]: \"China\", [SOURCE]: \"Nuclear\", [GENERATION]: 400 },\n  { [COUNTRY]: \"China\", [SOURCE]: \"Natural gas\", [GENERATION]: 300 },\n  { [COUNTRY]: \"China\", [SOURCE]: \"Coal\", [GENERATION]: 5200 },\n  { [COUNTRY]: \"USA\", [SOURCE]: \"Renewables\", [GENERATION]: 900 },\n  { [COUNTRY]: \"USA\", [SOURCE]: \"Nuclear\", [GENERATION]: 800 },\n  { [COUNTRY]: \"USA\", [SOURCE]: \"Natural gas\", [GENERATION]: 1700 },\n  { [COUNTRY]: \"USA\", [SOURCE]: \"Coal\", [GENERATION]: 700 },\n  { [COUNTRY]: \"Germany\", [SOURCE]: \"Renewables\", [GENERATION]: 270 },\n  { [COUNTRY]: \"Germany\", [SOURCE]: \"Nuclear\", [GENERATION]: 0 },\n  { [COUNTRY]: \"Germany\", [SOURCE]: \"Natural gas\", [GENERATION]: 80 },\n  { [COUNTRY]: \"Germany\", [SOURCE]: \"Coal\", [GENERATION]: 150 },\n  { [COUNTRY]: \"France\", [SOURCE]: \"Renewables\", [GENERATION]: 120 },\n  { [COUNTRY]: \"France\", [SOURCE]: \"Nuclear\", [GENERATION]: 320 },\n  { [COUNTRY]: \"France\", [SOURCE]: \"Natural gas\", [GENERATION]: 30 },\n  { [COUNTRY]: \"France\", [SOURCE]: \"Coal\", [GENERATION]: 5 },\n  { [COUNTRY]: \"Brazil\", [SOURCE]: \"Renewables\", [GENERATION]: 550 },\n  { [COUNTRY]: \"Brazil\", [SOURCE]: \"Nuclear\", [GENERATION]: 15 },\n  { [COUNTRY]: \"Brazil\", [SOURCE]: \"Natural gas\", [GENERATION]: 60 },\n  { [COUNTRY]: \"Brazil\", [SOURCE]: \"Coal\", [GENERATION]: 15 },\n  { [COUNTRY]: \"Norway\", [SOURCE]: \"Renewables\", [GENERATION]: 150 },\n  { [COUNTRY]: \"Norway\", [SOURCE]: \"Nuclear\", [GENERATION]: 0 },\n  { [COUNTRY]: \"Norway\", [SOURCE]: \"Natural gas\", [GENERATION]: 0.5 },\n  { [COUNTRY]: \"Norway\", [SOURCE]: \"Coal\", [GENERATION]: 0.1 },\n];\n\n// Plot: reads only data and the constants above\n// Sources stack in order of first appearance and keep that palette position in every bar\nconst sources = [...new Set(data.map((d) => d[SOURCE]))];\nconst countryList = [...new Set(data.map((d) => d[COUNTRY]))];\nconst valueOf = new Map(data.map((d) => [`${d[COUNTRY]}\\u0000${d[SOURCE]}`, d[GENERATION]]));\nconst countryTotals = new Map(\n  countryList.map((c) => [c, sources.reduce((a, s) => a + (valueOf.get(`${c}\\u0000${s}`) ?? 0), 0)]),\n);\nconst shareOf = new Map(\n  data.map((d) => [\n    `${d[COUNTRY]}\\u0000${d[SOURCE]}`,\n    d[GENERATION] == null || !countryTotals.get(d[COUNTRY]) ? null : (d[GENERATION] / countryTotals.get(d[COUNTRY])) * FULL,\n  ]),\n);\n\n// Bars ordered by the share of the first source, highest first\nconst countries = [...countryList].sort(\n  (a, b) => (shareOf.get(`${b}\\u0000${sources[0]}`) ?? 0) - (shareOf.get(`${a}\\u0000${sources[0]}`) ?? 0),\n);\nconst shares = sources.map((s) => countries.map((c) => shareOf.get(`${c}\\u0000${s}`) ?? null));\n\n// Segment label ink per source: whichever fixed ink contrasts more with the fill\nconst labelInks = sources.map((_, i) => {\n  const [R, G, B] = [1, 3, 5].map((k) => {\n    const c = parseInt(t.palette[i].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\nconst firstShares = shares[0];\nconst SUBTITLE = `${countries.length} grids, each normalized to its own total · sorted by ${sources[0].toLowerCase()} share: ${countries[0]} ${firstShares[0].toFixed(DECIMALS)}% to ${countries[countries.length - 1]} ${firstShares[firstShares.length - 1].toFixed(DECIMALS)}%`;\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      <BarChart\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        colors={t.palette}\n        skipAnimation\n        series={sources.map((s, i) => ({\n          id: `s${i}`,\n          label: s,\n          stack: \"share\",\n          data: shares[i],\n          valueFormatter: (v: number | null) => (v == null ? null : `${v.toFixed(DECIMALS)}%`),\n          barLabel: (item: { value: number | null }, ctx: { bar: { height: number } }) =>\n            item.value == null || ctx.bar.height < MIN_LABEL_PX ? null : `${item.value.toFixed(DECIMALS)}%`,\n        }))}\n        xAxis={[\n          {\n            scaleType: \"band\",\n            data: countries,\n            label: COUNTRY,\n            height: 64,\n            categoryGapRatio: 0.35,\n            disableTicks: true,\n            tickLabelStyle: { fontSize: 16, fill: t.ink },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            max: FULL,\n            label: `Share of ${COUNTRY.toLowerCase()} total (%)`,\n            width: 84,\n            disableTicks: true,\n            valueFormatter: (v: number) => `${v}%`,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        margin={{ top: 16, right: 40, bottom: 8, left: 24 }}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"top\", horizontal: \"center\" },\n            sx: { fontSize: 15, color: t.ink },\n          },\n        }}\n        sx={{\n          \"& .MuiBarChart-element\": { stroke: t.elevatedBg, strokeWidth: 1 },\n          \"& .MuiBarChart-label\": { fontSize: 15, fontWeight: 600 },\n          ...Object.fromEntries(sources.map((_, i) => [`& [data-series=\"s${i}\"] .MuiBarChart-label`, { fill: labelInks[i] }])),\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n        }}\n      />\n    </Box>\n  );\n}\n"}