{"spec_id":"calibration-beer-lambert","library":"muix","language":"javascript","code":"// anyplot.ai\n// calibration-beer-lambert: Beer-Lambert Calibration Curve\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-23\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { useXScale, useYScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\nconst THEME = window.ANYPLOT_THEME === \"dark\" ? \"dark\" : \"light\";\nconst INK_MUTED = THEME === \"dark\" ? \"#A8A79F\" : \"#6B6A63\";\n\n// Constants\nconst PREDICTION_LEVEL = 95; // two-sided prediction interval, percent\nconst GRID_POINTS = 40;\n\n// Columns: set these to your data's column names\nconst CONCENTRATION = \"Concentration (mg/L)\"; // role: concentration\nconst ABSORBANCE = \"Absorbance\"; // role: absorbance\nconst SAMPLE_TYPE = \"Sample type\"; // role: extra\n\n// Data: replace this block with your own records, one object per row\nconst data = [\n  { [CONCENTRATION]: 0, [ABSORBANCE]: 0.008, [SAMPLE_TYPE]: \"Calibration standards\" },\n  { [CONCENTRATION]: 2, [ABSORBANCE]: 0.178, [SAMPLE_TYPE]: \"Calibration standards\" },\n  { [CONCENTRATION]: 4, [ABSORBANCE]: 0.325, [SAMPLE_TYPE]: \"Calibration standards\" },\n  { [CONCENTRATION]: 6, [ABSORBANCE]: 0.512, [SAMPLE_TYPE]: \"Calibration standards\" },\n  { [CONCENTRATION]: 8, [ABSORBANCE]: 0.671, [SAMPLE_TYPE]: \"Calibration standards\" },\n  { [CONCENTRATION]: 10, [ABSORBANCE]: 0.845, [SAMPLE_TYPE]: \"Calibration standards\" },\n  { [CONCENTRATION]: 12, [ABSORBANCE]: 1.029, [SAMPLE_TYPE]: \"Calibration standards\" },\n  { [CONCENTRATION]: null, [ABSORBANCE]: 0.6, [SAMPLE_TYPE]: \"Unknown sample\" },\n];\n\n// Plot: reads only data and the constants above\nconst standards = data.filter((d) => d[CONCENTRATION] !== null);\nconst unknownRow = data.find((d) => d[CONCENTRATION] === null) ?? standards[Math.floor(standards.length / 2)];\nconst standardsLabel = standards[0][SAMPLE_TYPE];\nconst unknownSampleLabel = unknownRow[SAMPLE_TYPE];\nconst concentration = standards.map((d) => d[CONCENTRATION]);\nconst absorbance = standards.map((d) => d[ABSORBANCE]);\n\nconst n = standards.length;\nconst xMean = concentration.reduce((a, b) => a + b, 0) / n;\nconst yMean = absorbance.reduce((a, b) => a + b, 0) / n;\nlet sxy = 0;\nlet sxx = 0;\nfor (let i = 0; i < n; i += 1) {\n  sxy += (concentration[i] - xMean) * (absorbance[i] - yMean);\n  sxx += (concentration[i] - xMean) ** 2;\n}\nconst slope = sxy / sxx;\nconst intercept = yMean - slope * xMean;\n\nlet ssRes = 0;\nlet ssTot = 0;\nfor (let i = 0; i < n; i += 1) {\n  const fitted = intercept + slope * concentration[i];\n  ssRes += (absorbance[i] - fitted) ** 2;\n  ssTot += (absorbance[i] - yMean) ** 2;\n}\nconst rSquared = 1 - ssRes / ssTot;\nconst df = Math.max(1, n - 2);\nconst residualStdErr = Math.sqrt(ssRes / df);\n\n// Two-tailed t critical values by interval level (percent): df 1..30, then the\n// normal quantile. A level without a table fails loudly instead of mislabelling.\nconst T_CRIT: Record<number, { byDf: number[]; normal: number }> = {\n  95: {\n    byDf: [\n      12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228,\n      2.201, 2.179, 2.16, 2.145, 2.131, 2.12, 2.11, 2.101, 2.093, 2.086,\n      2.08, 2.074, 2.069, 2.064, 2.06, 2.056, 2.052, 2.048, 2.045, 2.042,\n    ],\n    normal: 1.96,\n  },\n};\nconst tTable = T_CRIT[PREDICTION_LEVEL];\nconst tCrit = df <= tTable.byDf.length ? tTable.byDf[df - 1] : tTable.normal;\n\nconst xMin = Math.min(...concentration);\nconst xMax = Math.max(...concentration);\nconst xPad = (xMax - xMin) * 0.03;\nconst xDomainMin = xMin - xPad;\nconst xDomainMax = xMax + xPad;\nconst gridX = Array.from(\n  { length: GRID_POINTS },\n  (_, i) => xMin + ((xMax - xMin) * i) / (GRID_POINTS - 1),\n);\nconst fittedY = gridX.map((x) => intercept + slope * x);\nconst halfWidth = gridX.map(\n  (x) =>\n    tCrit *\n    residualStdErr *\n    Math.sqrt(1 + 1 / n + (x - xMean) ** 2 / sxx),\n);\nconst upperY = fittedY.map((y, i) => y + halfWidth[i]);\nconst lowerY = fittedY.map((y, i) => y - halfWidth[i]);\n\nconst scatterData = standards.map((d, i) => ({\n  x: d[CONCENTRATION],\n  y: d[ABSORBANCE],\n  id: `std-${i}`,\n}));\n\nconst unknownAbsorbance = unknownRow[ABSORBANCE];\nconst unknownConcentration = (unknownAbsorbance - intercept) / slope;\n\nconst yAllValues = [...absorbance, ...upperY, ...lowerY, unknownAbsorbance, 0];\nconst yPad = (Math.max(...yAllValues) - Math.min(...yAllValues)) * 0.08;\nconst yDomainMin = Math.min(...yAllValues) - yPad;\nconst yDomainMax = Math.max(...yAllValues) + yPad;\n\nconst unitMatch = CONCENTRATION.match(/\\(([^)]+)\\)/);\nconst unitSuffix = unitMatch ? ` ${unitMatch[1]}` : \"\";\nconst equationLabel = `y = ${slope.toFixed(4)}x + ${intercept.toFixed(4)}   ·   R² = ${rSquared.toFixed(4)}`;\nconst unknownLabel = `${unknownSampleLabel}: A =${unknownAbsorbance.toFixed(2)} → c ≈ ${unknownConcentration.toFixed(2)}${unitSuffix}`;\n\nconst title = \"calibration-beer-lambert · javascript · muix · anyplot.ai\";\n\nfunction PredictionBand() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const top = gridX.map((x, i) => `${xScale(x)},${yScale(upperY[i])}`).join(\" L \");\n  const bottomIndices = [...gridX.keys()].reverse();\n  const bottom = bottomIndices\n    .map((i) => `${xScale(gridX[i])},${yScale(lowerY[i])}`)\n    .join(\" L \");\n  return <path d={`M ${top} L ${bottom} Z`} fill={INK_MUTED} opacity={0.2} stroke=\"none\" />;\n}\n\nfunction UnknownGuides() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const area = useDrawingArea();\n  const px = xScale(unknownConcentration);\n  const py = yScale(unknownAbsorbance);\n  const style = { stroke: INK_MUTED, strokeWidth: 2, strokeDasharray: \"8 6\" };\n  return (\n    <g>\n      <line x1={px} y1={py} x2={px} y2={area.top + area.height} style={style} />\n      <line x1={area.left} y1={py} x2={px} y2={py} style={style} />\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const headerH = 88;\n  const chartH = height - headerH;\n\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div\n        style={{\n          height: headerH,\n          padding: \"12px 64px 0 108px\",\n          display: \"flex\",\n          flexDirection: \"column\",\n          justifyContent: \"center\",\n        }}\n      >\n        <div\n          style={{\n            fontSize: 28,\n            fontWeight: 600,\n            color: t.ink,\n            textAlign: \"center\",\n            marginBottom: 4,\n          }}\n        >\n          {title}\n        </div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{equationLabel}</div>\n        <div style={{ fontSize: 15, color: INK_MUTED, marginTop: 2 }}>\n          Shaded band: {PREDICTION_LEVEL}% prediction interval · {unknownLabel}\n        </div>\n      </div>\n      <ChartsDataProvider\n        width={width}\n        height={chartH - 40}\n        margin={{ top: 4, right: 64, bottom: 24, left: 48 }}\n        series={[\n          {\n            type: \"scatter\",\n            id: \"standards\",\n            label: standardsLabel,\n            data: scatterData,\n            markerSize: 13,\n            color: t.palette[0],\n          },\n          {\n            type: \"scatter\",\n            id: \"unknown\",\n            label: unknownSampleLabel,\n            data: [{ x: unknownConcentration, y: unknownAbsorbance, id: \"unknown\" }],\n            markerSize: 15,\n            color: t.palette[1],\n          },\n          {\n            type: \"line\",\n            id: \"fit\",\n            data: fittedY,\n            curve: \"linear\",\n            color: t.ink,\n            showMark: false,\n            disableHighlight: true,\n          },\n        ]}\n        xAxis={[\n          {\n            data: gridX,\n            scaleType: \"linear\",\n            min: xDomainMin,\n            max: xDomainMax,\n            label: CONCENTRATION,\n            height: 72,\n            tickLabelStyle: { fontSize: 14 },\n            labelStyle: { fontSize: 16 },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: yDomainMin,\n            max: yDomainMax,\n            label: ABSORBANCE,\n            width: 60,\n            tickLabelStyle: { fontSize: 14 },\n            labelStyle: { fontSize: 16 },\n          },\n        ]}\n        skipAnimation\n      >\n        <ChartsWrapper\n          legendPosition={{ horizontal: \"end\", vertical: \"top\" }}\n          legendDirection=\"horizontal\"\n        >\n          <ChartsLegend sx={{ fontSize: 14, color: t.inkSoft, pr: 8 }} />\n          <ChartsSurface sx={{ \"& .MuiLineChart-line\": { strokeWidth: 3 } }}>\n            <ChartsGrid horizontal />\n            <PredictionBand />\n            <LinePlot skipAnimation />\n            <UnknownGuides />\n            <ChartsXAxis />\n            <ChartsYAxis />\n            <ScatterPlot />\n            <text\n              x={width - 64}\n              y={chartH - 52}\n              textAnchor=\"end\"\n              fontSize={14}\n              fill={INK_MUTED}\n            >\n              n = {n} standards{concentration.includes(0) ? \" (incl. blank)\" : \"\"}\n            </text>\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}