{"spec_id":"biplot-pca","library":"muix","language":"javascript","code":"// anyplot.ai\n// biplot-pca: PCA Biplot with Scores and Loading Vectors\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-24\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\nconst size = window.ANYPLOT_SIZE;\n\n// Constants\nconst LOADING_SCALE_SHARE = 0.85;\nconst AXIS_PAD_SHARE = 0.16;\nconst UNIT_CIRCLE_STEPS = 72;\nconst MIN_LABEL_GAP = 30;\nconst JACOBI_MAX_SWEEPS = 100;\nconst JACOBI_TOL = 1e-12;\n\n// Columns: set these to your data's column names\nconst LABELS = \"Production facility\"; // role: labels\nconst FEATURES = [\n  \"Temperature (°C)\",\n  \"Pressure (kPa)\",\n  \"Vibration (mm/s)\",\n  \"Throughput (units/min)\",\n]; // role: features\n\n// Data: replace this block with your own records, one object per row\nconst data = (() => {\n  let state = 42;\n  const facilities = [\"Munich Assembly\", \"Stuttgart Press\", \"Dresden Optics\"];\n  const batchOffsets = [-1.4, 0, 1.4];\n  const obsPerFacility = 20;\n  const rows: { [key: string]: string | number }[] = [];\n\n  for (let fIdx = 0; fIdx < facilities.length; fIdx += 1) {\n    const facility = facilities[fIdx];\n    for (let i = 0; i < obsPerFacility; i += 1) {\n      const normals: number[] = [];\n      for (let g = 0; g < 6; g += 1) {\n        state = (state * 16807) % 2147483647;\n        const u1 = Math.max((state - 1) / 2147483646, 1e-9);\n        state = (state * 16807) % 2147483647;\n        const u2 = (state - 1) / 2147483646;\n        normals.push(Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2));\n      }\n      const processIntensity = batchOffsets[fIdx] + normals[0] * 0.5;\n      const calibrationDrift = normals[1];\n      rows.push({\n        [LABELS]: facility,\n        [FEATURES[0]]: Number(\n          (68 + 4.2 * processIntensity + 1.0 * calibrationDrift + normals[2] * 1.4).toFixed(2),\n        ),\n        [FEATURES[1]]: Number(\n          (120 + 5.5 * processIntensity - 2.4 * calibrationDrift + normals[3] * 1.8).toFixed(2),\n        ),\n        [FEATURES[2]]: Number(\n          (3.2 - 1.2 * processIntensity + 2.6 * calibrationDrift + normals[4] * 0.35).toFixed(2),\n        ),\n        [FEATURES[3]]: Number(\n          (480 + 6.0 * processIntensity + 0.6 * calibrationDrift + normals[5] * 4.5).toFixed(2),\n        ),\n      });\n    }\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst sampleCount = data.length;\nconst featureCount = FEATURES.length;\n\nconst groups: string[] = [];\nfor (const row of data) {\n  const g = String(row[LABELS]);\n  if (!groups.includes(g)) groups.push(g);\n}\n\nconst featureMeans = FEATURES.map(\n  (col) => data.reduce((sum, row) => sum + Number(row[col]), 0) / sampleCount,\n);\nconst featureStds = FEATURES.map((col, j) =>\n  Math.sqrt(\n    data.reduce((sum, row) => sum + (Number(row[col]) - featureMeans[j]) ** 2, 0) /\n      sampleCount,\n  ) || 1,\n);\nconst standardized = data.map((row) =>\n  FEATURES.map((col, j) => (Number(row[col]) - featureMeans[j]) / featureStds[j]),\n);\n\nconst correlationMatrix = Array.from({ length: featureCount }, (_, rowIdx) =>\n  Array.from({ length: featureCount }, (_, colIdx) => {\n    let sum = 0;\n    for (let obs = 0; obs < sampleCount; obs += 1) {\n      sum += standardized[obs][rowIdx] * standardized[obs][colIdx];\n    }\n    return sum / sampleCount;\n  }),\n);\n\nconst workingMatrix = correlationMatrix.map((row) => row.slice());\nconst eigenvectors = Array.from({ length: featureCount }, (_, rowIdx) =>\n  Array.from({ length: featureCount }, (_, colIdx) => (rowIdx === colIdx ? 1 : 0)),\n);\n\nfor (let sweep = 0; sweep < JACOBI_MAX_SWEEPS; sweep += 1) {\n  let offDiagonalMagnitude = 0;\n  for (let rowIdx = 0; rowIdx < featureCount; rowIdx += 1) {\n    for (let colIdx = rowIdx + 1; colIdx < featureCount; colIdx += 1) {\n      offDiagonalMagnitude += workingMatrix[rowIdx][colIdx] ** 2;\n    }\n  }\n  if (offDiagonalMagnitude < JACOBI_TOL) break;\n\n  for (let p = 0; p < featureCount; p += 1) {\n    for (let q = p + 1; q < featureCount; q += 1) {\n      if (Math.abs(workingMatrix[p][q]) < JACOBI_TOL) continue;\n      const theta =\n        (workingMatrix[q][q] - workingMatrix[p][p]) / (2 * workingMatrix[p][q]);\n      const tan =\n        Math.sign(theta || 1) / (Math.abs(theta) + Math.sqrt(theta * theta + 1));\n      const cos = 1 / Math.sqrt(tan * tan + 1);\n      const sin = tan * cos;\n      const app = workingMatrix[p][p];\n      const aqq = workingMatrix[q][q];\n      const apq = workingMatrix[p][q];\n      workingMatrix[p][p] = cos * cos * app - 2 * sin * cos * apq + sin * sin * aqq;\n      workingMatrix[q][q] = sin * sin * app + 2 * sin * cos * apq + cos * cos * aqq;\n      workingMatrix[p][q] = 0;\n      workingMatrix[q][p] = 0;\n      for (let k = 0; k < featureCount; k += 1) {\n        if (k !== p && k !== q) {\n          const akp = workingMatrix[k][p];\n          const akq = workingMatrix[k][q];\n          workingMatrix[k][p] = cos * akp - sin * akq;\n          workingMatrix[p][k] = workingMatrix[k][p];\n          workingMatrix[k][q] = sin * akp + cos * akq;\n          workingMatrix[q][k] = workingMatrix[k][q];\n        }\n      }\n      for (let k = 0; k < featureCount; k += 1) {\n        const vkp = eigenvectors[k][p];\n        const vkq = eigenvectors[k][q];\n        eigenvectors[k][p] = cos * vkp - sin * vkq;\n        eigenvectors[k][q] = sin * vkp + cos * vkq;\n      }\n    }\n  }\n}\n\nconst eigenvalues = workingMatrix.map((row, i) => row[i]);\nconst componentOrder = eigenvalues\n  .map((value, index) => ({ value, index }))\n  .sort((a, b) => b.value - a.value);\nconst pc1Index = componentOrder[0].index;\nconst pc2Index = componentOrder[1].index;\nconst totalVariance = eigenvalues.reduce((sum, value) => sum + value, 0);\nconst pc1VarianceShare = (eigenvalues[pc1Index] / totalVariance) * 100;\nconst pc2VarianceShare = (eigenvalues[pc2Index] / totalVariance) * 100;\n\nconst scores = standardized.map((row) => ({\n  x: row.reduce((sum, value, j) => sum + value * eigenvectors[j][pc1Index], 0),\n  y: row.reduce((sum, value, j) => sum + value * eigenvectors[j][pc2Index], 0),\n}));\n\n// PC2's eigenvalue rounds to a tiny negative number when all features are collinear\nconst rawLoadings = FEATURES.map((_, j) => ({\n  x: eigenvectors[j][pc1Index] * Math.sqrt(eigenvalues[pc1Index]),\n  y: eigenvectors[j][pc2Index] * Math.sqrt(Math.max(0, eigenvalues[pc2Index])),\n}));\n\nconst maxScoreExtent = Math.max(\n  ...scores.map((s) => Math.max(Math.abs(s.x), Math.abs(s.y))),\n);\nconst maxLoadingExtent = Math.max(\n  ...rawLoadings.map((l) => Math.max(Math.abs(l.x), Math.abs(l.y))),\n);\nconst loadingDisplayScale = (maxScoreExtent * LOADING_SCALE_SHARE) / maxLoadingExtent;\nconst loadingVectors = rawLoadings.map((loading, j) => ({\n  variable: FEATURES[j],\n  x: loading.x * loadingDisplayScale,\n  y: loading.y * loadingDisplayScale,\n}));\n\nconst HEADER_H = 104;\nconst MARGIN = { top: 16, right: 200, bottom: 20, left: 200 };\nconst X_AXIS_H = 64;\nconst Y_AXIS_W = 84;\nconst drawW = size.width - MARGIN.left - MARGIN.right - Y_AXIS_W;\nconst drawH = size.height - HEADER_H - MARGIN.top - MARGIN.bottom - X_AXIS_H;\nconst aspectRatio = drawW / drawH;\n\nconst maxAbsX = Math.max(...scores.map((s) => Math.abs(s.x)), loadingDisplayScale);\nconst maxAbsY = Math.max(...scores.map((s) => Math.abs(s.y)), loadingDisplayScale);\nconst yBound = Math.max(maxAbsY * (1 + AXIS_PAD_SHARE), (maxAbsX * (1 + AXIS_PAD_SHARE)) / aspectRatio);\nconst yMax = yBound;\nconst yMin = -yBound;\nconst xMax = yBound * aspectRatio;\nconst xMin = -xMax;\n\nconst series = groups.map((group, groupIdx) => ({\n  type: \"scatter\" as const,\n  id: group,\n  label: group,\n  color: t.palette[groupIdx],\n  markerSize: 7,\n  xAxisId: \"pc1\",\n  yAxisId: \"pc2\",\n  data: data\n    .map((row, i) => ({ row, i }))\n    .filter(({ row }) => String(row[LABELS]) === group)\n    .map(({ i }) => ({ x: scores[i].x, y: scores[i].y, id: `${group}-${i}` })),\n}));\n\nconst unitCirclePoints = Array.from({ length: UNIT_CIRCLE_STEPS + 1 }, (_, i) => {\n  const angle = (i / UNIT_CIRCLE_STEPS) * 2 * Math.PI;\n  return {\n    x: Math.cos(angle) * loadingDisplayScale,\n    y: Math.sin(angle) * loadingDisplayScale,\n  };\n});\n\nconst TITLE = \"biplot-pca · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${sampleCount} observations · ${LABELS}: ${groups.length} · ${featureCount} standardized features · PC1 + PC2 explain ${(pc1VarianceShare + pc2VarianceShare).toFixed(1)}% variance`;\n\nfunction LoadingArrows() {\n  const xScale = useXScale(\"pc1\");\n  const yScale = useYScale(\"pc2\");\n  const originX = xScale(0);\n  const originY = yScale(0);\n\n  const rawItems = loadingVectors.map((loading) => ({\n    variable: loading.variable,\n    tipX: xScale(loading.x),\n    tipY: yScale(loading.y),\n    labelY: yScale(loading.y),\n    pointsRight: loading.x >= 0,\n  }));\n\n  const sides = [true, false].map((pointsRight) =>\n    rawItems\n      .filter((item) => item.pointsRight === pointsRight)\n      .sort((a, b) => a.tipY - b.tipY),\n  );\n  for (const side of sides) {\n    for (let i = 0; i < side.length; i += 1) {\n      const minY = i === 0 ? -Infinity : side[i - 1].labelY + MIN_LABEL_GAP;\n      side[i].labelY = Math.max(side[i].tipY, minY);\n    }\n  }\n  const items = sides.flat();\n\n  return (\n    <g>\n      <defs>\n        <marker\n          id=\"biplot-arrowhead\"\n          markerWidth={8}\n          markerHeight={8}\n          refX={6}\n          refY={4}\n          orient=\"auto\"\n        >\n          <path d=\"M0,0 L8,4 L0,8 Z\" fill={t.ink} />\n        </marker>\n      </defs>\n      <polyline\n        points={unitCirclePoints\n          .map((p) => `${xScale(p.x)},${yScale(p.y)}`)\n          .join(\" \")}\n        fill=\"none\"\n        stroke={t.inkSoft}\n        strokeWidth={1.25}\n        strokeDasharray=\"5 4\"\n        opacity={0.65}\n      />\n      <line\n        x1={xScale(xMin)}\n        x2={xScale(xMax)}\n        y1={originY}\n        y2={originY}\n        stroke={t.inkSoft}\n        strokeWidth={1}\n        strokeOpacity={0.45}\n      />\n      <line\n        x1={originX}\n        x2={originX}\n        y1={yScale(yMin)}\n        y2={yScale(yMax)}\n        stroke={t.inkSoft}\n        strokeWidth={1}\n        strokeOpacity={0.45}\n      />\n      {items.map((loading) => {\n        const textX = loading.tipX + (loading.pointsRight ? 12 : -12);\n        const pillW = loading.variable.length * 8.2 + 12;\n        const pillX = loading.pointsRight ? textX - 5 : textX - pillW + 5;\n        return (\n          <g key={loading.variable}>\n            <line\n              x1={originX}\n              y1={originY}\n              x2={loading.tipX}\n              y2={loading.tipY}\n              stroke={t.ink}\n              strokeWidth={2.5}\n              markerEnd=\"url(#biplot-arrowhead)\"\n            />\n            <rect\n              x={pillX}\n              y={loading.labelY - 12}\n              width={pillW}\n              height={24}\n              rx={4}\n              fill={t.pageBg}\n              fillOpacity={0.86}\n            />\n            <text\n              x={textX}\n              y={loading.labelY}\n              fill={t.ink}\n              fontSize={14}\n              fontWeight={600}\n              fontFamily=\"Inter, system-ui, sans-serif\"\n              textAnchor={loading.pointsRight ? \"start\" : \"end\"}\n              dominantBaseline=\"middle\"\n            >\n              {loading.variable}\n            </text>\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <div\n      style={{\n        width: size.width,\n        height: size.height,\n        background: t.pageBg,\n        fontFamily: \"Inter, system-ui, sans-serif\",\n        display: \"flex\",\n        flexDirection: \"column\",\n      }}\n    >\n      <div\n        style={{\n          height: HEADER_H,\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 6,\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>\n          {TITLE}\n        </div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</div>\n        <div style={{ display: \"flex\", alignItems: \"center\", gap: 24 }}>\n          {groups.map((group, idx) => (\n            <div\n              key={group}\n              style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}\n            >\n              <span\n                style={{\n                  width: 12,\n                  height: 12,\n                  borderRadius: \"50%\",\n                  background: t.palette[idx],\n                  display: \"inline-block\",\n                }}\n              />\n              <span style={{ fontSize: 14, color: t.inkSoft }}>{group}</span>\n            </div>\n          ))}\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <span\n              style={{\n                width: 18,\n                height: 0,\n                borderTop: `1.5px dashed ${t.inkSoft}`,\n                display: \"inline-block\",\n              }}\n            />\n            <span style={{ fontSize: 14, color: t.inkSoft }}>\n              Correlation unit circle\n            </span>\n          </div>\n        </div>\n      </div>\n\n      <ChartsContainer\n        width={size.width}\n        height={size.height - HEADER_H}\n        series={series}\n        xAxis={[\n          {\n            id: \"pc1\",\n            scaleType: \"linear\",\n            min: xMin,\n            max: xMax,\n            tickNumber: 11,\n            height: X_AXIS_H,\n            label: `PC1 (${pc1VarianceShare.toFixed(1)}% variance)`,\n            labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"pc2\",\n            scaleType: \"linear\",\n            min: yMin,\n            max: yMax,\n            tickNumber: 9,\n            width: Y_AXIS_W,\n            label: `PC2 (${pc2VarianceShare.toFixed(1)}% variance)`,\n            labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        margin={MARGIN}\n        skipAnimation\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      >\n        <ChartsGrid horizontal vertical />\n        <ScatterPlot />\n        <LoadingArrows />\n        <ChartsXAxis axisId=\"pc1\" />\n        <ChartsYAxis axisId=\"pc2\" />\n        <ChartsTooltip trigger=\"item\" />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}