{"spec_id":"histogram-2d","library":"muix","language":"javascript","code":"// anyplot.ai\n// histogram-2d: 2D Histogram Heatmap\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 86/100 | Updated: 2026-11-08\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ContinuousColorLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { useXScale, useYScale, useZColorScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst BINS_X = 26; // bin count along x\nconst BINS_Y = 18; // bin count along y\n\n// Columns: set these to your data's column names\nconst X = \"Tech Sector Fund Daily Return (%)\"; // role: x\nconst Y = \"Semiconductor Fund Daily Return (%)\"; // role: y\n\n// Data: replace this block with your own records, one object per point\n// Joint distribution of two correlated daily fund returns (correlation 0.65,\n// volatilities 1.4 % and 1.6 %): 8,000 days, far past what a scatter plot can show.\nconst data = (() => {\n  let seed = 42;\n  const random = () => {\n    seed = (seed + 0x6d2b79f5) | 0;\n    let s = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n    s = (s + Math.imul(s ^ (s >>> 7), 61 | s)) ^ s;\n    return ((s ^ (s >>> 14)) >>> 0) / 4294967296;\n  };\n  const gaussian = () => {\n    let u = 0;\n    let v = 0;\n    while (u === 0) u = random();\n    while (v === 0) v = random();\n    return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);\n  };\n  const correlation = 0.65;\n  return Array.from({ length: 8000 }, () => {\n    const z1 = gaussian();\n    const z2 = gaussian();\n    return {\n      [X]: Number((z1 * 1.4).toFixed(3)),\n      [Y]: Number(((correlation * z1 + Math.sqrt(1 - correlation * correlation) * z2) * 1.6).toFixed(3)),\n    };\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst xs = data.map((d) => d[X]);\nconst ys = data.map((d) => d[Y]);\nconst xMin = Math.min(...xs);\nconst xMax = Math.max(...xs);\nconst yMin = Math.min(...ys);\nconst yMax = Math.max(...ys);\nconst binWidth = (xMax - xMin) / BINS_X;\nconst binHeight = (yMax - yMin) / BINS_Y;\n\n// Count the points per rectangular bin; the last bin includes the maximum\nconst binCounts = new Array(BINS_X * BINS_Y).fill(0);\nfor (const d of data) {\n  const bx = Math.min(BINS_X - 1, Math.floor((d[X] - xMin) / binWidth));\n  const by = Math.min(BINS_Y - 1, Math.floor((d[Y] - yMin) / binHeight));\n  binCounts[by * BINS_X + bx] += 1;\n}\n// Empty bins are not drawn: the page shows through\nconst bins = binCounts\n  .map((count, k) => ({ id: k, x0: xMin + (k % BINS_X) * binWidth, y0: yMin + Math.floor(k / BINS_X) * binHeight, count }))\n  .filter((b) => b.count > 0);\nconst countMin = Math.min(...bins.map((b) => b.count));\nconst countMax = Math.max(...bins.map((b) => b.count));\n\n// Pearson correlation of the sample, for the subtitle\nconst xMean = xs.reduce((s, v) => s + v, 0) / xs.length;\nconst yMean = ys.reduce((s, v) => s + v, 0) / ys.length;\nlet sxy = 0;\nlet sxx = 0;\nlet syy = 0;\nfor (let i = 0; i < xs.length; i += 1) {\n  sxy += (xs[i] - xMean) * (ys[i] - yMean);\n  sxx += (xs[i] - xMean) ** 2;\n  syy += (ys[i] - yMean) ** 2;\n}\nconst pearsonR = sxy / Math.sqrt(sxx * syy);\n\nconst TITLE = \"Correlated Fund Returns ·histogram-2d · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `n = ${data.length.toLocaleString(\"en-US\")} · ${BINS_X} × ${BINS_Y} bins · Pearson r = ${pearsonR.toFixed(2)}`;\nconst LEGEND_LABEL = \"Points per bin (log scale)\";\nconst HEADER_H = 82;\nconst LEGEND_H = 76;\n\n// Bins in data coordinates, coloured by the z axis colour map\nfunction HistogramCells() {\n  const xScale = useXScale() as (v: number) => number;\n  const yScale = useYScale() as (v: number) => number;\n  const colorScale = useZColorScale() as (v: number) => string;\n  return (\n    <g>\n      {bins.map((b) => {\n        const left = xScale(b.x0);\n        const right = xScale(b.x0 + binWidth);\n        const top = yScale(b.y0 + binHeight);\n        const bottom = yScale(b.y0);\n        return (\n          <rect\n            key={b.id}\n            x={left}\n            y={top}\n            width={right - left}\n            height={bottom - top}\n            fill={colorScale(Math.log(b.count))}\n            stroke={colorScale(Math.log(b.count))}\n            strokeWidth={0.5}\n          />\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartH = height - HEADER_H;\n\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\", overflow: \"hidden\" }}>\n      <Box sx={{ height: HEADER_H, pt: \"16px\", 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.5 }}>{SUBTITLE}</Typography>\n      </Box>\n      <ChartsDataProvider\n        width={width}\n        height={chartH - LEGEND_H}\n        series={[]}\n        skipAnimation\n        margin={{ top: 16, right: 48, bottom: 8, left: 32 }}\n        xAxis={[\n          {\n            scaleType: \"linear\",\n            min: xMin,\n            max: xMax,\n            height: 64,\n            label: X,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: yMin,\n            max: yMax,\n            width: 72,\n            label: Y,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        // Log colour scale: bin counts fall off steeply from the core to the tails\n        zAxis={[\n          {\n            colorMap: { type: \"continuous\", min: Math.log(countMin), max: Math.log(countMax), color: [t.seq[0], t.seq[1]] },\n          },\n        ]}\n      >\n        <ChartsWrapper\n          legendPosition={{ vertical: \"bottom\", horizontal: \"center\" }}\n          legendDirection=\"horizontal\"\n          sx={{ width, height: chartH }}\n        >\n          <Box\n            sx={{\n              gridArea: \"legend\",\n              height: LEGEND_H,\n              width: width * 0.4,\n              display: \"flex\",\n              flexDirection: \"column\",\n              pt: \"4px\",\n              boxSizing: \"border-box\",\n            }}\n          >\n            <Typography sx={{ color: t.ink, fontSize: 15, textAlign: \"center\", mb: \"4px\" }}>{LEGEND_LABEL}</Typography>\n            <ContinuousColorLegend\n              direction=\"horizontal\"\n              thickness={16}\n              labelPosition=\"end\"\n              minLabel={({ value }) => String(Math.round(Math.exp(Number(value))))}\n              maxLabel={({ value }) => String(Math.round(Math.exp(Number(value))))}\n              sx={{ color: t.inkSoft, fontSize: 14 }}\n            />\n          </Box>\n          <ChartsSurface>\n            <HistogramCells />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </Box>\n  );\n}\n"}