{"spec_id":"scatter-lag","library":"muix","language":"javascript","code":"// anyplot.ai\n// scatter-lag: Lag Plot for Time Series Autocorrelation Diagnosis\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\n\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ContinuousColorLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { useXScale, useYScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst LAG = 1; // lag order k (the spec's lag role): each observation is paired with the one k steps later\nconst EXTENT_PAD_SHARE = 0.07; // room beyond the extreme values, as a share of the value span\nconst POINT_OPACITY = 0.85;\nconst TICK_COUNT = 12; // about this many ticks on each axis, so both share one step\n\n// Columns: set these to your data's column names\nconst HOUR = \"Hour of record\"; // role: extra\nconst TEMPERATURE = \"Temperature (°C)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Hourly station temperature as an AR(1) process: rho 0.97 around 20 °C, sigma about 5 °C,\n// so one-hour changes stay within a few degrees.\nconst data = (() => {\n  let seed = 42;\n  const uniform = () => {\n    seed = (1664525 * seed + 1013904223) >>> 0;\n    return seed / 4294967296;\n  };\n  const rho = 0.97;\n  let state = 0;\n  const rows = [];\n  for (let hour = 0; hour < 200; hour += 1) {\n    if (hour > 0) {\n      const u = uniform();\n      const v = uniform();\n      const shock = Math.sqrt(-2 * Math.log(u + 1e-15)) * Math.cos(2 * Math.PI * v);\n      state = rho * state + Math.sqrt(1 - rho * rho) * shock;\n    }\n    rows.push({ [HOUR]: hour, [TEMPERATURE]: Number((20 + state * 5).toFixed(2)) });\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst series = [...data].sort((a, b) => a[HOUR] - b[HOUR]);\nconst pairs = series.slice(LAG).map((later, i) => ({\n  id: `pair-${i}`,\n  x: series[i][TEMPERATURE],\n  y: later[TEMPERATURE],\n  z: series[i][HOUR],\n}));\n\n// Pearson r of the lagged pairs\nconst n = pairs.length;\nconst xMean = pairs.reduce((s, p) => s + p.x, 0) / n;\nconst yMean = pairs.reduce((s, p) => s + p.y, 0) / n;\nconst cov = pairs.reduce((s, p) => s + (p.x - xMean) * (p.y - yMean), 0);\nconst sx = Math.sqrt(pairs.reduce((s, p) => s + (p.x - xMean) ** 2, 0));\nconst sy = Math.sqrt(pairs.reduce((s, p) => s + (p.y - yMean) ** 2, 0));\nconst pearsonR = cov / (sx * sy);\n\n// Both axes show the same variable, so they share one padded range and y = x is the plot's diagonal\nconst values = series.map((d) => d[TEMPERATURE]);\nconst pad = (Math.max(...values) - Math.min(...values)) * EXTENT_PAD_SHARE;\nconst axisMin = Math.min(...values) - pad;\nconst axisMax = Math.max(...values) + pad;\nconst hours = pairs.map((p) => p.z);\nconst hourMin = Math.min(...hours);\nconst hourMax = Math.max(...hours);\n\nconst TITLE = \"scatter-lag · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `Lag k = ${LAG} · ${n} pairs from ${series.length} observations · dashed line: y = x`;\nconst HEADER_HEIGHT = 76;\nconst LEGEND_WIDTH = 150;\nconst LEGEND_HEIGHT = 420;\n\nfunction DiagonalAndR() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const { left, top, width } = useDrawingArea();\n  // Positive autocorrelation leaves the top-left corner empty, negative leaves the top-right\n  const onLeft = pearsonR >= 0;\n  return (\n    <g>\n      <line\n        x1={xScale(axisMin)}\n        y1={yScale(axisMin)}\n        x2={xScale(axisMax)}\n        y2={yScale(axisMax)}\n        stroke={t.inkSoft}\n        strokeOpacity={0.6}\n        strokeWidth={2}\n        strokeDasharray=\"10 8\"\n      />\n      <text\n        x={onLeft ? left + 20 : left + width - 20}\n        y={top + 34}\n        textAnchor={onLeft ? \"start\" : \"end\"}\n        fontSize={18}\n        fontWeight={600}\n        fill={t.ink}\n        stroke={t.pageBg}\n        strokeWidth={4}\n        paintOrder=\"stroke\"\n      >\n        {`r(lag ${LAG}) = ${pearsonR.toFixed(3)}`}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div\n        style={{\n          height: HEADER_HEIGHT,\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 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</div>\n      </div>\n      <ChartsDataProvider\n        width={width - LEGEND_WIDTH}\n        height={height - HEADER_HEIGHT}\n        margin={{ top: 8, right: 24, bottom: 16, left: 24 }}\n        skipAnimation\n        series={[\n          {\n            type: \"scatter\",\n            id: \"pairs\",\n            label: `${TEMPERATURE} at t + ${LAG}`,\n            data: pairs,\n            markerSize: 6,\n            zAxisId: \"time\",\n          },\n        ]}\n        xAxis={[\n          {\n            id: \"earlier\",\n            scaleType: \"linear\",\n            min: axisMin,\n            max: axisMax,\n            label: `${TEMPERATURE} at t`,\n            tickNumber: TICK_COUNT,\n            height: 64,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 17, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"later\",\n            scaleType: \"linear\",\n            min: axisMin,\n            max: axisMax,\n            label: `${TEMPERATURE} at t + ${LAG}`,\n            tickNumber: TICK_COUNT,\n            width: 76,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 17, fill: t.ink },\n          },\n        ]}\n        zAxis={[\n          {\n            id: \"time\",\n            min: hourMin,\n            max: hourMax,\n            colorMap: { type: \"continuous\", min: hourMin, max: hourMax, color: [t.seq[0], t.seq[1]] },\n          },\n        ]}\n      >\n        <ChartsWrapper legendPosition={{ vertical: \"middle\", horizontal: \"end\" }} legendDirection=\"vertical\">\n          <div\n            style={{\n              gridArea: \"legend\",\n              width: LEGEND_WIDTH,\n              height: LEGEND_HEIGHT,\n              display: \"flex\",\n              flexDirection: \"column\",\n              alignItems: \"center\",\n            }}\n          >\n            <div style={{ color: t.ink, fontSize: 16, marginBottom: 10, textAlign: \"center\" }}>{HOUR}</div>\n            <ContinuousColorLegend\n              axisDirection=\"z\"\n              axisId=\"time\"\n              direction=\"vertical\"\n              thickness={18}\n              labelPosition=\"end\"\n              sx={{ flex: 1, color: t.inkSoft, fontSize: 15 }}\n            />\n          </div>\n          <ChartsSurface\n            sx={{\n              \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n              \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n              \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n              \"& .MuiScatterChart-marker\": { fillOpacity: POINT_OPACITY },\n            }}\n          >\n            <ChartsGrid horizontal vertical />\n            <ChartsXAxis />\n            <ChartsYAxis />\n            <DiagonalAndR />\n            <ScatterPlot />\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}