{"spec_id":"timeseries-forecast-uncertainty","library":"muix","language":"javascript","code":"// anyplot.ai\n// timeseries-forecast-uncertainty: Time Series Forecast with Uncertainty Band\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/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 { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { useXScale, useYScale } 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 LEVEL_80 = 80; // confidence levels of the two bands (%)\nconst LEVEL_95 = 95;\nconst OPACITY_80 = 0.38; // the narrower band is darker\nconst OPACITY_95 = 0.18;\nconst PAD_SHARE = 0.06; // room above and below the outermost values and bounds\nconst UNIT_SUFFIX = /\\s*\\([^)]*\\)\\s*$/; // a trailing \"(unit)\" in a column name\nconst HEADER_H = 112;\nconst MARGIN = { top: 16, right: 40, bottom: 8, left: 16 };\n\n// Columns: set these to your data's column names\nconst DATE = \"Month\"; // role: date\nconst ACTUAL = \"Demand (units)\"; // role: actual\nconst FORECAST = \"Forecast (units)\"; // role: forecast\nconst LOWER_80 = \"80% lower bound (units)\"; // role: lower_80\nconst UPPER_80 = \"80% upper bound (units)\"; // role: upper_80\nconst LOWER_95 = \"95% lower bound (units)\"; // role: lower_95\nconst UPPER_95 = \"95% upper bound (units)\"; // role: upper_95\n\n// Data: replace this block with your own records, one object per row\n// Monthly product demand: 42 months of history and a 12-month forecast whose first\n// month repeats the last observation, with normal intervals that widen with the horizon\nconst data = (() => {\n  let state = 42;\n  const random = () => {\n    state = (state * 1103515245 + 12345) % 2147483648;\n    return state / 2147483648;\n  };\n  const history = 42;\n  const start = history - 1;\n  const centre = (i: number) => 3200 + 9 * i + 260 * Math.sin((2 * Math.PI * i) / 12);\n  return Array.from({ length: history + 12 }, (_, i) => {\n    const actual = i <= start ? Math.round(centre(i) + (random() - 0.5) * 180) : null;\n    const forecast = i < start ? null : i === start ? actual : Math.round(centre(i));\n    const sigma = 70 + 26 * (i - start);\n    return {\n      [DATE]: new Date(2023, i, 1),\n      [ACTUAL]: actual,\n      [FORECAST]: forecast,\n      [LOWER_80]: forecast == null ? null : Math.round(forecast - 1.2816 * sigma),\n      [UPPER_80]: forecast == null ? null : Math.round(forecast + 1.2816 * sigma),\n      [LOWER_95]: forecast == null ? null : Math.round(forecast - 1.96 * sigma),\n      [UPPER_95]: forecast == null ? null : Math.round(forecast + 1.96 * sigma),\n    };\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst rows = data\n  .filter((d) => d[DATE] instanceof Date && !Number.isNaN(d[DATE].getTime()))\n  .sort((a, b) => a[DATE].getTime() - b[DATE].getTime());\nconst dates = rows.map((d) => d[DATE]);\nconst forecastRows = rows.filter((d) => Number.isFinite(d[FORECAST]));\nconst forecastStart = forecastRows[0][DATE];\nconst historyRows = rows.filter((d) => Number.isFinite(d[ACTUAL]));\nconst horizon = forecastRows.filter((d) => !Number.isFinite(d[ACTUAL])).length;\nconst values = rows\n  .flatMap((d) => [ACTUAL, FORECAST, LOWER_80, UPPER_80, LOWER_95, UPPER_95].map((k) => d[k]))\n  .filter((v) => Number.isFinite(v));\nconst vMin = Math.min(...values);\nconst vMax = Math.max(...values);\n// the wider band is drawn first, so the narrower one lies on top of it\nconst bands = [\n  { id: \"ci95\", level: LEVEL_95, lower: LOWER_95, upper: UPPER_95, opacity: OPACITY_95 },\n  { id: \"ci80\", level: LEVEL_80, lower: LOWER_80, upper: UPPER_80, opacity: OPACITY_80 },\n].map((b) => ({ ...b, rows: rows.filter((d) => Number.isFinite(d[b.lower]) && Number.isFinite(d[b.upper])) }));\nconst formatMonth = (d: Date) => d.toLocaleDateString(\"en-US\", { month: \"short\", year: \"numeric\" });\nconst legend = [\n  { key: \"actual\", label: ACTUAL.replace(UNIT_SUFFIX, \"\"), dash: false, opacity: 0 },\n  { key: \"forecast\", label: FORECAST.replace(UNIT_SUFFIX, \"\"), dash: true, opacity: 0 },\n  { key: \"ci80\", label: `${LEVEL_80}% interval`, dash: false, opacity: 1 - (1 - OPACITY_80) * (1 - OPACITY_95) },\n  { key: \"ci95\", label: `${LEVEL_95}% interval`, dash: false, opacity: OPACITY_95 },\n];\n\nconst TITLE = \"Monthly Demand Forecast · timeseries-forecast-uncertainty · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${historyRows.length} ${DATE.toLowerCase()}s of history to ${formatMonth(historyRows[historyRows.length - 1][DATE])} · ${horizon}-${DATE.toLowerCase()} forecast with ${LEVEL_80}% and ${LEVEL_95}% intervals`;\nconst axisText = { tickLabelStyle: { fontSize: 14, fill: t.inkSoft }, labelStyle: { fontSize: 16, fill: t.ink } };\n\nfunction BandLayer() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g>\n      {bands.map((b) => (\n        <path\n          key={b.id}\n          d={`M ${b.rows.map((d) => `${xScale(d[DATE])} ${yScale(d[b.upper])}`).join(\" L \")} L ${[...b.rows]\n            .reverse()\n            .map((d) => `${xScale(d[DATE])} ${yScale(d[b.lower])}`)\n            .join(\" L \")} Z`}\n          fill={t.palette[0]}\n          fillOpacity={b.opacity}\n          stroke=\"none\"\n        />\n      ))}\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: HEADER_H, px: \"56px\", pt: \"14px\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ color: t.ink, fontSize: 22, fontWeight: 600, lineHeight: 1.25 }}>{TITLE}</Typography>\n        <Typography sx={{ color: t.inkSoft, fontSize: 15, mt: \"4px\" }}>{SUBTITLE}</Typography>\n        <Box sx={{ display: \"flex\", gap: \"26px\", mt: \"12px\", alignItems: \"center\" }}>\n          {legend.map((item) => (\n            <Box key={item.key} sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n              {item.opacity > 0 ? (\n                <Box sx={{ width: 20, height: 14, bgcolor: t.palette[0], opacity: item.opacity }} />\n              ) : (\n                <Box sx={{ width: 26, height: 0, borderTop: `3px ${item.dash ? \"dashed\" : \"solid\"} ${t.palette[0]}` }} />\n              )}\n              <Typography sx={{ color: t.inkSoft, fontSize: 15 }}>{item.label}</Typography>\n            </Box>\n          ))}\n        </Box>\n      </Box>\n      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_H}\n        skipAnimation\n        margin={MARGIN}\n        xAxis={[\n          {\n            data: dates,\n            scaleType: \"time\",\n            min: dates[0],\n            max: dates[dates.length - 1],\n            tickNumber: 10,\n            valueFormatter: formatMonth,\n            label: DATE,\n            height: 60,\n            ...axisText,\n          },\n        ]}\n        yAxis={[\n          {\n            min: vMin - (vMax - vMin) * PAD_SHARE,\n            max: vMax + (vMax - vMin) * PAD_SHARE,\n            label: ACTUAL,\n            width: 84,\n            valueFormatter: (v: number) => v.toLocaleString(\"en-US\"),\n            ...axisText,\n          },\n        ]}\n        series={[\n          { type: \"line\", id: \"actual\", label: legend[0].label, data: rows.map((d) => d[ACTUAL]), color: t.palette[0], showMark: false, curve: \"monotoneX\" },\n          { type: \"line\", id: \"forecast\", label: legend[1].label, data: rows.map((d) => d[FORECAST]), color: t.palette[0], showMark: false, curve: \"linear\" },\n        ]}\n      >\n        <ChartsWrapper>\n          <ChartsSurface\n            sx={{\n              \"& .MuiLineChart-line\": { strokeWidth: 3 },\n              '& .MuiLineChart-line[data-series=\"forecast\"]': { strokeDasharray: \"10 6\" },\n              \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n              \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n              \"& .MuiChartsGrid-line\": { stroke: t.grid },\n            }}\n          >\n            <ChartsGrid horizontal />\n            <BandLayer />\n            <LinePlot />\n            <ChartsReferenceLine\n              x={forecastStart}\n              label=\"Forecast start\"\n              labelAlign=\"start\"\n              lineStyle={{ stroke: t.inkSoft, strokeDasharray: \"4 4\", strokeWidth: 1.5 }}\n              labelStyle={{ fontSize: 14, fill: t.inkSoft }}\n            />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n          <ChartsTooltip trigger=\"axis\" />\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </Box>\n  );\n}\n"}