{"spec_id":"line-timeseries-rolling","library":"muix","language":"javascript","code":"// anyplot.ai\n// line-timeseries-rolling: Time Series with Rolling Average Overlay\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 86/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst DAY_MS = 86_400_000;\nconst Y_PAD_SHARE = 0.06; // share of the value range added below and above the lines\n\n// Columns: set these to your data's column names\nconst DATE = \"Date\"; // role: date\nconst VISITORS = \"Unique visitors\"; // role: value\nconst ROLLING = \"Rolling average\"; // role: rolling_avg\n\n// Data: replace this block with your own records, one object per row\n// Daily unique visitors to a blog over 120 days: weekend dips, a slow climb, a two-week surge\n// after a viral post, day-to-day noise, and the trailing 7-day mean (empty until the window is full).\nconst data = (() => {\n  let seed = 42;\n  const rand = () => {\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    return seed / 0x7fffffff;\n  };\n  const WINDOW_DAYS = 7;\n  const visitors = Array.from({ length: 120 }, (_, day) => {\n    const date = new Date(2026, 0, 1 + day);\n    const weekendDip = date.getDay() === 0 || date.getDay() === 6 ? 0.62 : 1;\n    const surge = day >= 58 && day <= 74 ? 1 + 0.5 * Math.sin(((day - 58) / 16) * Math.PI) : 1;\n    const noise = 1 + (rand() - 0.5) * 0.22;\n    return { date, value: Math.max(300, Math.round(2200 * weekendDip * (1 + day * 0.004) * surge * noise)) };\n  });\n  return visitors.map((v, i) => ({\n    [DATE]: v.date,\n    [VISITORS]: v.value,\n    [ROLLING]:\n      i < WINDOW_DAYS - 1\n        ? null\n        : Math.round(visitors.slice(i - WINDOW_DAYS + 1, i + 1).reduce((s, w) => s + w.value, 0) / WINDOW_DAYS),\n  }));\n})();\n\n// Plot: reads only data and the constants above\nconst rows = [...data].sort((a, b) => a[DATE] - b[DATE]);\nconst dates = rows.map((d) => d[DATE]);\nconst raw = rows.map((d) => d[VISITORS]);\nconst rolling = rows.map((d) => d[ROLLING]);\n\n// The trailing window is as long as the run of observations before the first rolling value, plus one\nconst firstRolling = rolling.findIndex((v) => v != null);\nconst windowSize = firstRolling + 1;\nconst stepDays = Math.round((dates[1] - dates[0]) / DAY_MS);\nconst windowLabel = stepDays === 1 ? `${windowSize}-day` : `${windowSize}-point`;\n\nconst values = [...raw, ...rolling].filter((v) => v != null);\nconst yLow = Math.min(...values);\nconst yHigh = Math.max(...values);\nconst yPad = (yHigh - yLow) * Y_PAD_SHARE;\nconst formatDay = (d: Date) => d.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\", year: \"numeric\" });\nconst formatCount = (v: number | null) => (v == null ? \"\" : v.toLocaleString(\"en-US\"));\n\nconst TITLE = \"Daily Unique Visitors · line-timeseries-rolling · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${rows.length} observations · ${formatDay(dates[0])} to ${formatDay(dates[dates.length - 1])} · trailing ${windowLabel} mean from ${formatDay(dates[firstRolling])}`;\nconst HEADER_H = 80;\nconst LEGEND_H = 44;\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 112px\", 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      <LineChart\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        skipAnimation\n        grid={{ horizontal: true, vertical: true }}\n        margin={{ top: 12, right: 48, bottom: 16, left: 24 }}\n        xAxis={[\n          {\n            data: dates,\n            scaleType: \"time\",\n            tickNumber: 10,\n            valueFormatter: (v: Date, context) =>\n              context.location === \"tick\" ? v.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\" }) : formatDay(v),\n            label: DATE,\n            height: 64,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: yLow - yPad,\n            max: yHigh + yPad,\n            tickNumber: 8,\n            label: VISITORS,\n            width: 84,\n            valueFormatter: (v: number) => v.toLocaleString(\"en-US\"),\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={[\n          {\n            id: \"raw\",\n            data: raw,\n            label: `Raw data · ${VISITORS}`,\n            color: t.palette[0],\n            curve: \"linear\",\n            showMark: false,\n            valueFormatter: formatCount,\n          },\n          {\n            id: \"rolling\",\n            data: rolling,\n            label: `${ROLLING} (${windowLabel})`,\n            color: t.palette[1],\n            curve: \"monotoneX\",\n            showMark: false,\n            valueFormatter: formatCount,\n          },\n        ]}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"top\", horizontal: \"end\" },\n            sx: { fontSize: 16, color: t.ink, columnGap: 3, pr: 5 },\n          },\n        }}\n        sx={{\n          '& .MuiLineChart-line[data-series=\"raw\"]': { strokeWidth: 1.75, strokeOpacity: 0.65 },\n          '& .MuiLineChart-line[data-series=\"rolling\"]': { strokeWidth: 4 },\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      />\n    </div>\n  );\n}\n"}