{"spec_id":"histogram-density","library":"muix","language":"javascript","code":"// anyplot.ai\n// histogram-density: Density Histogram\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 86/100 | Updated: 2026-10-24\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { BarPlot } from \"@mui/x-charts/BarChart\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { axisClasses } from \"@mui/x-charts/ChartsAxis\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst FONT = \"system-ui, -apple-system, sans-serif\";\nconst TITLE = \"histogram-density · javascript · muix · anyplot.ai\";\nconst BIN_COUNT = 18;\nconst Y_HEADROOM_RATIO = 0.15;\n\nconst BRAND = t.palette[0];\nconst CURVE = t.palette[1];\n\n// Columns: set these to your data's column names\nconst WEIGHT = \"Package weight (g)\"; // role: values\n\n// Data: replace this block with your own records\ntype DensityRow = {\n  [WEIGHT]: number;\n};\n\nconst data: DensityRow[] = [];\nlet seed = 7 >>> 0;\nconst sampleSize = 400;\n\nfor (let i = 0; i < sampleSize; i++) {\n  seed = (Math.imul(1664525, seed) + 1013904223) >>> 0;\n  const u1 = Math.max(seed / 0x100000000, 1e-10);\n  seed = (Math.imul(1664525, seed) + 1013904223) >>> 0;\n  const u2 = seed / 0x100000000;\n  const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n  data.push({\n    [WEIGHT]: Number((500 + z * 6).toFixed(3)),\n  });\n}\n\n// Plot: reads only data and the constants above\nconst weights = data.map((r) => r[WEIGHT]);\nconst n = weights.length;\nconst dataMin = Math.min(...weights);\nconst dataMax = Math.max(...weights);\nconst binWidth = (dataMax - dataMin) / BIN_COUNT;\n\nconst binCounts = new Array(BIN_COUNT).fill(0);\nfor (const w of weights) {\n  const idx = Math.min(BIN_COUNT - 1, Math.floor((w - dataMin) / binWidth));\n  binCounts[idx] += 1;\n}\n\nconst density = binCounts.map((c) => c / (n * binWidth));\nconst binCenters = binCounts.map((_, i) => dataMin + (i + 0.5) * binWidth);\n\nconst sampleMean = weights.reduce((s, w) => s + w, 0) / n;\nconst sampleSd = Math.sqrt(\n  weights.reduce((s, w) => s + (w - sampleMean) ** 2, 0) / (n - 1),\n);\nconst normalPdf = binCenters.map((x) => {\n  const z = (x - sampleMean) / sampleSd;\n  return Math.exp(-0.5 * z * z) / (sampleSd * Math.sqrt(2 * Math.PI));\n});\n\nconst yMax = Math.max(...density, ...normalPdf) * (1 + Y_HEADROOM_RATIO);\n\nconst unitMatch = WEIGHT.match(/\\(([^)]+)\\)/);\nconst unitStr = unitMatch ? unitMatch[1] : \"\";\nconst unitSuffix = unitStr ? ` ${unitStr}` : \"\";\nconst SUBTITLE = `${WEIGHT} (n = ${n}, bin width = ${binWidth.toFixed(2)}${unitSuffix}) · Mean ${sampleMean.toFixed(1)}${unitSuffix}, SD ${sampleSd.toFixed(1)}${unitSuffix}`;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const HEADER_H = 76;\n  const LEGEND_H = 40;\n\n  return (\n    <Box\n      sx={{\n        width,\n        height,\n        bgcolor: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n        overflow: \"hidden\",\n      }}\n    >\n      <Typography\n        sx={{\n          fontSize: 22,\n          fontWeight: 600,\n          color: t.ink,\n          pt: \"14px\",\n          px: \"40px\",\n          pb: 0,\n          lineHeight: 1.2,\n          fontFamily: FONT,\n        }}\n      >\n        {TITLE}\n      </Typography>\n      <Typography\n        sx={{\n          fontSize: 15,\n          fontWeight: 400,\n          color: t.inkSoft,\n          px: \"40px\",\n          pt: \"4px\",\n          pb: 0,\n          lineHeight: 1.2,\n          fontFamily: FONT,\n        }}\n      >\n        {SUBTITLE}\n      </Typography>\n\n      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        series={[\n          {\n            type: \"bar\",\n            id: \"observed\",\n            data: density,\n            label: `Observed density (${BIN_COUNT} bins)`,\n            labelMarkType: \"square\",\n            color: BRAND,\n          },\n          {\n            type: \"line\",\n            id: \"fitted\",\n            data: normalPdf,\n            label: \"Fitted Normal PDF\",\n            labelMarkType: \"line\",\n            color: CURVE,\n            showMark: false,\n            curve: \"monotoneX\",\n          },\n        ]}\n        xAxis={[\n          {\n            id: \"weight-axis\",\n            scaleType: \"band\",\n            data: binCenters,\n            categoryGapRatio: 0.02,\n            height: 60,\n            label: WEIGHT,\n            valueFormatter: (v: number) => v.toFixed(1),\n            tickLabelInterval: (_v: number, i: number) => i % 2 === 0,\n            labelStyle: { fontSize: 15, fill: t.ink, fontFamily: FONT },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontFamily: FONT },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"density-axis\",\n            min: 0,\n            max: yMax,\n            width: 96,\n            label: unitStr ? `Probability Density (1/${unitStr})` : \"Probability Density\",\n            valueFormatter: (v: number) => v.toFixed(3),\n            labelStyle: { fontSize: 15, fill: t.ink, fontFamily: FONT },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontFamily: FONT },\n          },\n        ]}\n        margin={{ top: 20, right: 40, bottom: 20, left: 20 }}\n        skipAnimation\n      >\n        <ChartsWrapper\n          legendPosition={{ horizontal: \"start\", vertical: \"top\" }}\n          legendDirection=\"horizontal\"\n        >\n          <ChartsLegend\n            sx={{\n              fontSize: 14,\n              fontWeight: 600,\n              color: t.ink,\n              fontFamily: FONT,\n              px: \"40px\",\n              pt: \"8px\",\n              gap: \"24px\",\n            }}\n          />\n          <ChartsSurface>\n            <ChartsGrid\n              horizontal\n              sx={{ \"& line\": { stroke: t.grid, strokeWidth: 0.8 } }}\n            />\n            <BarPlot skipAnimation />\n            <LinePlot\n              skipAnimation\n              slotProps={{ line: { sx: { strokeWidth: 3.5 } } }}\n            />\n            <ChartsXAxis\n              axisId=\"weight-axis\"\n              sx={{\n                [`& .${axisClasses.line}`]: { stroke: t.grid },\n                [`& .${axisClasses.tick}`]: { stroke: t.grid },\n              }}\n            />\n            <ChartsYAxis\n              axisId=\"density-axis\"\n              sx={{\n                [`& .${axisClasses.line}`]: { stroke: t.grid },\n                [`& .${axisClasses.tick}`]: { stroke: t.grid },\n              }}\n            />\n          </ChartsSurface>\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </Box>\n  );\n}\n"}