{"spec_id":"boxen-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// boxen-basic: Basic Boxen Plot (Letter-Value Plot)\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 88/100 | Updated: 2026-10-24\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst MAX_LEVELS = 5;\nconst WIDTH_FACTORS = [1.0, 0.8, 0.62, 0.46, 0.32];\nconst LEVEL_MIX = [0.86, 0.68, 0.52, 0.37, 0.24];\nconst LEVEL_NAMES = [\n  \"Fourths (50%)\",\n  \"Eighths (75%)\",\n  \"Sixteenths (87.5%)\",\n  \"32nds (93.8%)\",\n  \"64ths (96.9%)\",\n];\nconst Y_LOW_FACTOR = 0.85;\nconst Y_HIGH_FACTOR = 1.15;\nconst BASE_WIDTH_SHARE = 0.56;\nconst HEADER_H = 108;\n\n// Columns: set these to your data's column names\nconst CATEGORY = \"Service endpoint\"; // role: category\nconst VALUE = \"Response time (ms)\"; // role: value\n\n// Data: replace this block with your own records, one object per row\nconst data = (() => {\n  let state = 42;\n  const endpoints = [\n    { name: \"/api/search\", medianMs: 45, sigma: 0.3 },\n    { name: \"/api/profile\", medianMs: 65, sigma: 0.35 },\n    { name: \"/api/checkout\", medianMs: 120, sigma: 0.45 },\n    { name: \"/api/upload\", medianMs: 260, sigma: 0.55 },\n  ];\n  const nPerEndpoint = 1500;\n  const rows: { [key: string]: string | number }[] = [];\n\n  for (const ep of endpoints) {\n    const mu = Math.log(ep.medianMs);\n    for (let i = 0; i < nPerEndpoint; i += 1) {\n      state = (state * 1664525 + 1013904223) % 4294967296;\n      const u1 = Math.max(state / 4294967296, 1e-9);\n      state = (state * 1664525 + 1013904223) % 4294967296;\n      const u2 = state / 4294967296;\n      const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n      const val = Math.exp(mu + ep.sigma * z);\n      rows.push({\n        [CATEGORY]: ep.name,\n        [VALUE]: Number(val.toFixed(2)),\n      });\n    }\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst categories: string[] = [];\nfor (const row of data) {\n  const c = String(row[CATEGORY]);\n  if (!categories.includes(c)) categories.push(c);\n}\n\nconst bgInt = parseInt(t.pageBg.slice(1), 16);\nconst bgRgb = [(bgInt >> 16) & 255, (bgInt >> 8) & 255, bgInt & 255];\n\nconst categoryStats = categories.map((name, ci) => {\n  const values = data\n    .filter((row) => String(row[CATEGORY]) === name)\n    .map((row) => Number(row[VALUE]))\n    .sort((a, b) => a - b);\n  const n = values.length;\n\n  let depth = (n + 1) / 2;\n  const medLo = Math.floor(depth) - 1;\n  const medHi = Math.ceil(depth) - 1;\n  const median = (values[medLo] + values[medHi]) / 2;\n\n  const boxes: { lower: number; upper: number }[] = [];\n  for (let i = 0; i < MAX_LEVELS; i += 1) {\n    const nextDepth = (Math.floor(depth) + 1) / 2;\n    if (nextDepth === depth) break;\n    depth = nextDepth;\n    const loIdx1 = Math.floor(depth) - 1;\n    const loIdx2 = Math.ceil(depth) - 1;\n    const lower = (values[loIdx1] + values[loIdx2]) / 2;\n\n    const upDepth = n - depth + 1;\n    const hiIdx1 = Math.floor(upDepth) - 1;\n    const hiIdx2 = Math.ceil(upDepth) - 1;\n    const upper = (values[hiIdx1] + values[hiIdx2]) / 2;\n\n    boxes.push({ lower, upper });\n  }\n\n  const outer = boxes[boxes.length - 1] ?? { lower: median, upper: median };\n  const outliers = values.filter((v) => v < outer.lower || v > outer.upper);\n\n  const colHex = t.palette[ci];\n  const colInt = parseInt(colHex.slice(1), 16);\n  const colRgb = [(colInt >> 16) & 255, (colInt >> 8) & 255, colInt & 255];\n  const levelFills = LEVEL_MIX.map((mix) => {\n    const r = Math.round(bgRgb[0] + (colRgb[0] - bgRgb[0]) * mix);\n    const g = Math.round(bgRgb[1] + (colRgb[1] - bgRgb[1]) * mix);\n    const b = Math.round(bgRgb[2] + (colRgb[2] - bgRgb[2]) * mix);\n    return `rgb(${r}, ${g}, ${b})`;\n  });\n\n  return { name, median, boxes, outer, outliers, color: colHex, levelFills };\n});\n\nconst allExtremes = categoryStats.flatMap((s) => [\n  s.outer.lower,\n  s.outer.upper,\n  ...s.outliers,\n]);\nconst yMin = Math.min(...allExtremes) * Y_LOW_FACTOR;\nconst yMax = Math.max(...allExtremes) * Y_HIGH_FACTOR;\nconst levelsDrawn = Math.max(...categoryStats.map((s) => s.boxes.length));\nconst levelLabels = LEVEL_NAMES.slice(0, levelsDrawn);\n\nconst TITLE = \"API Response Times · boxen-basic · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${data.length.toLocaleString(\"en-US\")} observations · ${categories.length} groups (${CATEGORY}) · ${levelsDrawn} letter-value levels`;\n\nfunction BoxenLayer() {\n  const xScale = useXScale(\"endpoints\");\n  const yScale = useYScale(\"latency\");\n  const bandwidth = xScale.bandwidth();\n  const baseWidth = bandwidth * BASE_WIDTH_SHARE;\n\n  return (\n    <g>\n      {categoryStats.map((cat) => {\n        const center = xScale(cat.name) + bandwidth / 2;\n        const innerWidth = baseWidth * WIDTH_FACTORS[0];\n        const yMed = yScale(cat.median);\n\n        return (\n          <g key={cat.name}>\n            {[...cat.boxes].reverse().map((box, ri) => {\n              const idx = cat.boxes.length - 1 - ri;\n              const w = baseWidth * WIDTH_FACTORS[idx];\n              const yTop = yScale(box.upper);\n              const yBottom = yScale(box.lower);\n              return (\n                <rect\n                  key={idx}\n                  x={center - w / 2}\n                  y={yTop}\n                  width={w}\n                  height={Math.max(1, yBottom - yTop)}\n                  rx={2}\n                  fill={cat.levelFills[idx]}\n                  stroke={cat.color}\n                  strokeWidth={1.4}\n                />\n              );\n            })}\n            <line\n              x1={center - innerWidth / 2}\n              x2={center + innerWidth / 2}\n              y1={yMed}\n              y2={yMed}\n              stroke={t.pageBg}\n              strokeWidth={5}\n              strokeLinecap=\"round\"\n            />\n            <line\n              x1={center - innerWidth / 2}\n              x2={center + innerWidth / 2}\n              y1={yMed}\n              y2={yMed}\n              stroke={t.ink}\n              strokeWidth={2.5}\n              strokeLinecap=\"round\"\n            />\n            {cat.outliers.map((v, j) => (\n              <circle\n                key={j}\n                cx={center}\n                cy={yScale(v)}\n                r={4.5}\n                fill={t.pageBg}\n                stroke={cat.color}\n                strokeWidth={1.8}\n              />\n            ))}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const chartHeight = window.ANYPLOT_SIZE.height - HEADER_H;\n  const legendSwatches = categoryStats[0].levelFills;\n  const brand = t.palette[0];\n\n  return (\n    <div\n      style={{\n        width: window.ANYPLOT_SIZE.width,\n        height: window.ANYPLOT_SIZE.height,\n        background: t.pageBg,\n        fontFamily: \"Inter, system-ui, sans-serif\",\n        display: \"flex\",\n        flexDirection: \"column\",\n      }}\n    >\n      <div\n        style={{\n          height: HEADER_H,\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 }}>\n          {TITLE}\n        </div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</div>\n        <div\n          style={{\n            display: \"flex\",\n            alignItems: \"center\",\n            gap: 22,\n            fontSize: 14,\n            color: t.inkSoft,\n          }}\n        >\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 7 }}>\n            <div style={{ width: 16, height: 2.5, background: t.ink }} />\n            <span>Median</span>\n          </div>\n          {levelLabels.map((label, idx) => (\n            <div\n              key={label}\n              style={{ display: \"flex\", alignItems: \"center\", gap: 7 }}\n            >\n              <div\n                style={{\n                  width: 14,\n                  height: 14,\n                  borderRadius: 3,\n                  background: legendSwatches[idx],\n                  border: `1.2px solid ${brand}`,\n                }}\n              />\n              <span>{label}</span>\n            </div>\n          ))}\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 7 }}>\n            <div\n              style={{\n                width: 10,\n                height: 10,\n                borderRadius: \"50%\",\n                background: t.pageBg,\n                border: `1.8px solid ${brand}`,\n              }}\n            />\n            <span>Outliers</span>\n          </div>\n        </div>\n      </div>\n\n      <ChartsContainer\n        width={window.ANYPLOT_SIZE.width}\n        height={chartHeight}\n        series={[]}\n        skipAnimation\n        margin={{ top: 20, right: 40, bottom: 20, left: 40 }}\n        xAxis={[\n          {\n            id: \"endpoints\",\n            data: categories,\n            scaleType: \"band\",\n            height: 64,\n            label: CATEGORY,\n            labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"latency\",\n            scaleType: \"log\",\n            min: yMin,\n            max: yMax,\n            width: 88,\n            label: VALUE,\n            labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": {\n            stroke: t.grid,\n            opacity: 0.65,\n            strokeDasharray: \"3 4\",\n          },\n        }}\n      >\n        <ChartsGrid horizontal />\n        <BoxenLayer />\n        <ChartsXAxis axisId=\"endpoints\" />\n        <ChartsYAxis axisId=\"latency\" />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}