{"spec_id":"line-confidence","library":"muix","language":"javascript","code":"// anyplot.ai\n// line-confidence: Line Plot with Confidence Interval\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/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 { ChartsAxisHighlight } from \"@mui/x-charts/ChartsAxisHighlight\";\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 BAND_OPACITY = 0.24;\nconst Y_PAD_SHARE = 0.06; // share of the value range added above the upper and below the lower bound\n\n// Columns: set these to your data's column names\nconst DATE = \"Date\"; // role: x\nconst USERS = \"Daily active users (forecast mean)\"; // role: y\nconst LOWER = \"Lower bound (users)\"; // role: y_lower\nconst UPPER = \"Upper bound (users)\"; // role: y_upper\nconst BAND_LABEL = \"95 % prediction interval\"; // what the two bound columns describe: change it with them\n\n// Data: replace this block with your own records, one object per x value\n// A 60-day forecast of daily active users from 1 Jan 2024: a rising trend with a two-week\n// cycle, and a 95 % prediction interval whose standard error grows with the horizon.\nconst data = Array.from({ length: 60 }, (_, i) => {\n  const mean = 12000 + 45 * i + 800 * Math.sin((2 * Math.PI * i) / 14);\n  const half = 1.96 * (300 + 25 * i);\n  return {\n    [DATE]: new Date(Date.UTC(2024, 0, 1 + i)).toISOString().slice(0, 10),\n    [USERS]: Math.round(mean),\n    [LOWER]: Math.round(mean - half),\n    [UPPER]: Math.round(mean + half),\n  };\n});\n\n// Plot: reads only data and the constants above\n// ISO dates are read as local midnight, the frame the time axis places its ticks in\nconst rows = [...data].sort((a, b) => Date.parse(a[DATE]) - Date.parse(b[DATE]));\nconst n = rows.length;\nconst dates = rows.map((d) => new Date(`${d[DATE]}T00:00:00`));\nconst centre = rows.map((d) => d[USERS] ?? null);\nconst lowers = rows.map((d) => d[LOWER] ?? null);\nconst uppers = rows.map((d) => d[UPPER] ?? null);\n\n// The band is filled for each run of consecutive x values that has both bounds\nconst bandRuns: number[][] = [];\nrows.forEach((_, i) => {\n  if (lowers[i] == null || uppers[i] == null) return;\n  const run = bandRuns[bandRuns.length - 1];\n  if (run && run[run.length - 1] === i - 1) run.push(i);\n  else bandRuns.push([i]);\n});\n\nconst drawn = [...centre, ...lowers, ...uppers].filter((v) => v != null);\nconst yLow = Math.min(...drawn);\nconst yHigh = Math.max(...drawn);\nconst yPad = (yHigh - yLow) * Y_PAD_SHARE;\n\nconst widths = rows.map((_, i) => (lowers[i] != null && uppers[i] != null ? uppers[i] - lowers[i] : null));\nconst firstWidth = widths.find((w) => w != null);\nconst lastWidth = [...widths].reverse().find((w) => w != null);\n\nconst dayFormat = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\" });\nconst fullFormat = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\", year: \"numeric\" });\nconst numberFormat = new Intl.NumberFormat(\"en-US\");\nconst boundUnit = LOWER.match(/\\(([^)]+)\\)/)?.[1];\nconst unitSuffix = boundUnit ? ` ${boundUnit}` : \"\";\n\nconst TITLE = \"line-confidence · javascript · muix · anyplot.ai\";\nconst SUBTITLE =\n  `${n} days, ${fullFormat.format(dates[0])} – ${fullFormat.format(dates[n - 1])}` +\n  (firstWidth != null\n    ? ` · band width ${numberFormat.format(firstWidth)}${unitSuffix} at the start, ${numberFormat.format(lastWidth)}${unitSuffix} at the end`\n    : \"\");\nconst HEADER_H = 84;\nconst LEGEND_H = 40;\nconst LINE_COLOR = t.palette[0];\n\nfunction Band() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g>\n      {bandRuns.map((run) => {\n        const top = run.map((i) => `${xScale(dates[i])},${yScale(uppers[i])}`);\n        const bottom = [...run].reverse().map((i) => `${xScale(dates[i])},${yScale(lowers[i])}`);\n        return (\n          <path\n            key={run[0]}\n            d={`M${top.join(\"L\")}L${bottom.join(\"L\")}Z`}\n            fill={LINE_COLOR}\n            fillOpacity={BAND_OPACITY}\n            stroke=\"none\"\n          />\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\", overflow: \"hidden\" }}>\n      <Box sx={{ height: HEADER_H, pt: \"14px\", textAlign: \"center\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.3 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.6 }}>{SUBTITLE}</Typography>\n      </Box>\n      <Box\n        sx={{ height: LEGEND_H, display: \"flex\", alignItems: \"center\", justifyContent: \"center\", gap: \"36px\" }}\n      >\n        <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"10px\" }}>\n          <Box sx={{ width: 28, height: 4, borderRadius: 2, bgcolor: LINE_COLOR }} />\n          <Typography sx={{ fontSize: 15, color: t.ink }}>{USERS}</Typography>\n        </Box>\n        <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"10px\" }}>\n          <Box sx={{ width: 28, height: 16, borderRadius: \"3px\", bgcolor: LINE_COLOR, opacity: BAND_OPACITY }} />\n          <Typography sx={{ fontSize: 15, color: t.ink }}>{BAND_LABEL}</Typography>\n        </Box>\n      </Box>\n      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        margin={{ top: 8, right: 48, bottom: 16, left: 20 }}\n        skipAnimation\n        series={[\n          {\n            type: \"line\",\n            id: \"centre\",\n            data: centre,\n            label: USERS,\n            color: LINE_COLOR,\n            curve: \"linear\",\n            showMark: false,\n            valueFormatter: (v, { dataIndex }) =>\n              v == null\n                ? \"\"\n                : `${numberFormat.format(v)} (${numberFormat.format(lowers[dataIndex])} – ${numberFormat.format(uppers[dataIndex])})`,\n          },\n        ]}\n        xAxis={[\n          {\n            scaleType: \"time\",\n            data: dates,\n            domainLimit: \"strict\",\n            tickNumber: 9,\n            valueFormatter: (v: Date, context) =>\n              context.location === \"tick\" ? dayFormat.format(v) : fullFormat.format(v),\n            label: DATE,\n            height: 64,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: yLow - yPad,\n            max: yHigh + yPad,\n            width: 84,\n            label: USERS,\n            valueFormatter: (v: number) => numberFormat.format(v),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n      >\n        <ChartsWrapper>\n          <ChartsSurface\n            sx={{\n              \"& .MuiLineChart-line\": { strokeWidth: 3.5 },\n              \"& .MuiChartsGrid-line\": { stroke: t.grid },\n            }}\n          >\n            <ChartsGrid horizontal />\n            <Band />\n            <LinePlot skipAnimation />\n            <ChartsAxisHighlight x=\"line\" />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n          <ChartsTooltip trigger=\"axis\" />\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </Box>\n  );\n}\n"}