{"spec_id":"line-pca-variance-cumulative","library":"muix","language":"javascript","code":"// anyplot.ai\n// line-pca-variance-cumulative: Cumulative Explained Variance for PCA Component Selection\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 91/100 | Updated: 2026-11-08\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\nimport { ChartsAxisHighlight } from \"@mui/x-charts/ChartsAxisHighlight\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { BarPlot } from \"@mui/x-charts/BarChart\";\nimport { LinePlot, MarkPlot } from \"@mui/x-charts/LineChart\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst THRESHOLDS = [0.9, 0.95]; // the common component-selection thresholds\nconst ELBOW_MIN_GAP = 0.1; // an elbow counts as detectable when the normalised curve rises this far above its chord\nconst Y_DOMAIN_MAX = 1; // cumulative share of the total variance\nconst Y_HEAD_SHARE = 0.05; // headroom above 100 % so the last marker stays whole\nconst BAR_GAP = 0.45; // share of each component's band left empty around its bar\n\n// Columns: set these to your data's column names\nconst COMPONENT = \"Number of principal components\"; // role: n_components\nconst RATIO = \"Explained variance\"; // role: explained_variance_ratio\n\n// Data: replace this block with your own records, one object per row\n// PCA on 16 standardised vibration, temperature and pressure sensors of a rotating pump:\n// geometrically decaying eigenvalues, as is typical for correlated sensor arrays.\nconst data = (() => {\n  const eigenvalues = [28, 17, 13, 9.5, 7, 5.5, 4.2, 3.2, 2.4, 1.9, 1.5, 1.2, 0.95, 0.75, 0.6, 0.5];\n  const total = eigenvalues.reduce((s, v) => s + v, 0);\n  return eigenvalues.map((v, i) => ({ [COMPONENT]: i + 1, [RATIO]: v / total }));\n})();\n\n// Plot: reads only data and the constants above\nconst rows = [...data].sort((a, b) => a[COMPONENT] - b[COMPONENT]);\nconst components = rows.map((d) => d[COMPONENT]);\nconst ratios = rows.map((d) => d[RATIO]);\nconst cumulative = ratios.map((_, i) => ratios.slice(0, i + 1).reduce((s, v) => s + v, 0));\nconst n = components.length;\nconst pct = (v: number) => `${(v * 100).toFixed(1)}%`;\n\n// First component count whose cumulative share reaches each threshold\nconst hits = THRESHOLDS.map((thr) => ({ thr, k: components[cumulative.findIndex((v) => v >= thr)] }));\n\n// Elbow: the count where the normalised curve sits farthest above the chord from first to last point\nconst xNorm = components.map((c) => (c - components[0]) / (components[n - 1] - components[0]));\nconst yNorm = cumulative.map((v) => (v - cumulative[0]) / (cumulative[n - 1] - cumulative[0]));\nconst gaps = yNorm.map((v, i) => v - xNorm[i]);\nconst elbowIdx = gaps.indexOf(Math.max(...gaps));\nconst hasElbow = gaps[elbowIdx] >= ELBOW_MIN_GAP;\n\nconst TITLE = \"line-pca-variance-cumulative · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${n} components · largest single share ${pct(Math.max(...ratios))} · smallest ${pct(Math.min(...ratios))}`;\nconst HEADER_H = 80;\nconst LEGEND_H = 44;\n\n// A ring and a label on the elbow's own marker\nfunction ElbowMark() {\n  const xScale = useXScale<\"band\">();\n  const yScale = useYScale() as (v: number) => number;\n  if (!hasElbow) return null;\n  const x = (xScale(components[elbowIdx]) ?? 0) + xScale.bandwidth() / 2;\n  const y = yScale(cumulative[elbowIdx]);\n  return (\n    <g>\n      <circle cx={x} cy={y} r={14} fill=\"none\" stroke={t.ink} strokeWidth={2} />\n      <text x={x + 20} y={y + 34} fontSize={15} fontWeight={600} fill={t.ink}>\n        Elbow at {components[elbowIdx]} components, {pct(cumulative[elbowIdx])}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: HEADER_H, padding: \"16px 40px 0 104px\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.25 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, marginTop: 6 }}>{SUBTITLE}</div>\n      </div>\n      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        skipAnimation\n        margin={{ top: 12, right: 48, bottom: 16, left: 24 }}\n        xAxis={[\n          {\n            id: \"components\",\n            data: components,\n            scaleType: \"band\",\n            categoryGapRatio: BAR_GAP,\n            valueFormatter: (v: number) => `${v}`,\n            label: COMPONENT,\n            height: 64,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"share\",\n            min: 0,\n            max: Y_DOMAIN_MAX * (1 + Y_HEAD_SHARE),\n            tickNumber: 6,\n            label: `${RATIO} (%)`,\n            width: 76,\n            valueFormatter: (v: number) => `${Math.round(v * 100)}%`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={[\n          {\n            type: \"line\",\n            id: \"cumulative\",\n            label: `Cumulative ${RATIO.toLowerCase()}`,\n            data: cumulative,\n            color: t.palette[0],\n            curve: \"monotoneX\",\n            showMark: true,\n            shape: \"circle\",\n            labelMarkType: \"line+mark\",\n            valueFormatter: (v: number | null) => (v == null ? \"\" : pct(v)),\n          },\n          {\n            type: \"bar\",\n            id: \"individual\",\n            label: `${RATIO} per component`,\n            data: ratios,\n            color: t.palette[1],\n            labelMarkType: \"square\",\n            valueFormatter: (v: number | null) => (v == null ? \"\" : pct(v)),\n          },\n        ]}\n      >\n        <ChartsWrapper legendPosition={{ vertical: \"top\", horizontal: \"end\" }} legendDirection=\"horizontal\">\n          <ChartsLegend\n            sx={{\n              fontSize: 16,\n              color: t.ink,\n              columnGap: 3,\n              pr: 5,\n              \"& .MuiChartsLegend-mark\": { width: 24, height: 24 },\n              // Legend glyphs drawn like the series: the cumulative mark filled, the bars as translucent as the plot's\n              '& .MuiChartsLegend-item[data-series=\"cumulative\"] .MuiChartsLegend-mark path:last-of-type': { fill: t.palette[0] },\n              '& .MuiChartsLegend-item[data-series=\"individual\"] .MuiChartsLegend-mark': { opacity: 0.55 },\n            }}\n          />\n          <ChartsSurface\n            sx={{\n              '& [data-series=\"individual\"] .MuiBarChart-element': { fillOpacity: 0.55 },\n              '& .MuiLineChart-line[data-series=\"cumulative\"]': { strokeWidth: 3.5 },\n              '& .MuiLineChart-mark[data-series=\"cumulative\"]': { r: 6, fill: t.palette[0], stroke: t.pageBg, 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            <ChartsGrid horizontal />\n            {/* Bars first, so the per-component shares sit behind the cumulative curve */}\n            <BarPlot borderRadius={3} skipAnimation />\n            {hits.map(({ thr, k }) => (\n              <ChartsReferenceLine\n                key={thr}\n                y={thr}\n                label={k == null ? `${pct(thr)} not reached` : `${pct(thr)} reached at ${k} components`}\n                labelAlign=\"start\"\n                spacing={{ x: 12, y: 6 }}\n                lineStyle={{ stroke: t.inkSoft, strokeWidth: 1.75, strokeDasharray: \"8 5\" }}\n                labelStyle={{ fontSize: 15, fill: t.ink }}\n              />\n            ))}\n            <ChartsAxisHighlight x=\"band\" />\n            <LinePlot skipAnimation />\n            <MarkPlot skipAnimation />\n            <ElbowMark />\n            <ChartsXAxis axisId=\"components\" />\n            <ChartsYAxis axisId=\"share\" />\n          </ChartsSurface>\n          <ChartsTooltip trigger=\"axis\" />\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}