{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "box-plot",
  "type": "registry:component",
  "title": "Box Plot",
  "description": "The spread of a measure in each of several groups side by side: a box from the first to the third quartile, the median across it, whiskers to the furthest values within 1.5 boxes, and the values beyond them as points; or, as a violin, the shape of each spread.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-array",
    "d3-shape"
  ],
  "devDependencies": [
    "@types/d3-array",
    "@types/d3-shape"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/box-plot.tsx",
      "type": "registry:component",
      "target": "components/viz/box-plot.tsx",
      "content": "\"use client\";\n/**\n * @name box-plot\n * @category viz\n * @description The spread of a measure in each of several groups side by side: a box from the first to the third quartile, the median across it, whiskers to the furthest values within 1.5 boxes, and the values beyond them as points; or, as a violin, the shape of each spread.\n * @when Comparing distributions across groups: which is higher, which is wider, which has outliers. For one group's full shape use histogram; for a few exact numbers per group use bar-chart or dot-plot.\n * @example\n * <BoxPlot\n *   label=\"Response time by region\"\n *   data={[\n *     { region: \"North\", ms: 120 }, { region: \"North\", ms: 140 }, { region: \"North\", ms: 135 }, { region: \"North\", ms: 310 },\n *     { region: \"South\", ms: 90 }, { region: \"South\", ms: 110 }, { region: \"South\", ms: 105 }, { region: \"South\", ms: 98 },\n *   ]}\n *   group=\"region\"\n *   value=\"ms\"\n *   valueLabel=\"Milliseconds\"\n * />\n */\nimport { deviation, quantileSorted } from \"d3-array\";\nimport { area, curveBasis } from \"d3-shape\";\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartAxis,\n  ChartContainer,\n  ChartEmpty,\n  ChartGrid,\n  chartLinear,\n  chartSeries,\n  ChartSvg,\n  ChartTooltip,\n  fitText,\n  formatNumber,\n  readNumber,\n  useChartCursor,\n  widestText,\n  type ChartBaseProps,\n} from \"@/components/viz/chart\";\n\nexport type BoxPlotProps<T extends object> = ChartBaseProps & {\n  /** One object per observation. */\n  data: readonly T[];\n  /** The field naming each observation's group. */\n  group: keyof T & string;\n  /** The field holding the measured number. */\n  value: keyof T & string;\n  /** The groups in order. Default: in order of first appearance. */\n  groups?: readonly string[];\n  /** \"box\" (quartiles and whiskers) or \"violin\" (the shape of the spread, with the quartiles inside). */\n  variant?: \"box\" | \"violin\";\n  /** Draw every group in the first series colour (default) or each in its own. */\n  colorBy?: \"none\" | \"group\";\n  /** The measure's name, in the tooltip and the table. Default: the field name. */\n  valueLabel?: string;\n  /** Words for the statistics, in the tooltip and the table. */\n  labels?: Partial<BoxPlotLabels>;\n  showGrid?: boolean;\n};\n\nexport type BoxPlotLabels = {\n  count: string;\n  low: string;\n  q1: string;\n  median: string;\n  q3: string;\n  high: string;\n  outliers: string;\n};\n\nconst LABELS: BoxPlotLabels = {\n  count: \"Count\",\n  low: \"Lowest\",\n  q1: \"First quartile\",\n  median: \"Median\",\n  q3: \"Third quartile\",\n  high: \"Highest\",\n  outliers: \"Outliers\",\n};\nconst ROUND = \"[rx:min(var(--radius),4px)] [ry:min(var(--radius),4px)]\";\n\ntype Summary = {\n  name: string;\n  count: number;\n  low: number;\n  q1: number;\n  median: number;\n  q3: number;\n  high: number;\n  outliers: number[];\n  sorted: number[];\n};\n\nfunction summarise(name: string, values: number[]): Summary {\n  const sorted = [...values].sort((a, b) => a - b);\n  const q1 = quantileSorted(sorted, 0.25) ?? 0;\n  const median = quantileSorted(sorted, 0.5) ?? 0;\n  const q3 = quantileSorted(sorted, 0.75) ?? 0;\n  const reach = 1.5 * (q3 - q1);\n  const inside = sorted.filter((v) => v >= q1 - reach && v <= q3 + reach);\n  return {\n    name,\n    count: sorted.length,\n    low: inside[0] ?? q1,\n    high: inside[inside.length - 1] ?? q3,\n    q1,\n    median,\n    q3,\n    outliers: sorted.filter((v) => v < q1 - reach || v > q3 + reach),\n    sorted,\n  };\n}\n\n/** A Gaussian kernel density estimate over `points`, with Silverman's bandwidth. */\nfunction density(sorted: number[], points: number[]): number[] {\n  const n = sorted.length;\n  const sd = deviation(sorted) ?? 0;\n  const bandwidth = Math.max(1e-9, 1.06 * (sd || Math.abs(sorted[0] ?? 1) * 0.1 || 1) * Math.pow(n, -0.2));\n  return points.map((p) => sorted.reduce((sum, v) => sum + Math.exp(-0.5 * ((p - v) / bandwidth) ** 2), 0) / (n * bandwidth * Math.sqrt(2 * Math.PI)));\n}\n\nexport function BoxPlot<T extends object>({\n  data,\n  group,\n  value,\n  groups,\n  variant = \"box\",\n  colorBy = \"none\",\n  valueLabel,\n  labels: given,\n  showGrid = true,\n  label,\n  aspect,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: BoxPlotProps<T>) {\n  const labels = { ...LABELS, ...given };\n  const summaries = useMemo(() => {\n    const byGroup = new Map<string, number[]>();\n    for (const name of groups ?? []) byGroup.set(name, []);\n    for (const row of data) {\n      const number = readNumber(row, value);\n      if (number === null) continue;\n      const name = String((row as Record<string, unknown>)[group] ?? \"\");\n      if (groups && !byGroup.has(name)) continue;\n      const list = byGroup.get(name) ?? [];\n      list.push(number);\n      byGroup.set(name, list);\n    }\n    return [...byGroup].filter(([, values]) => values.length > 0).map(([name, values]) => summarise(name, values));\n  }, [data, group, value, groups]);\n\n  const cursor = useChartCursor(summaries.length);\n  const number = formatValue ?? ((amount: number) => formatNumber(amount, locale));\n  const table = {\n    caption: label,\n    columns: [`${group} (${valueLabel ?? value})`, labels.count, labels.low, labels.q1, labels.median, labels.q3, labels.high, labels.outliers],\n    rows: summaries.map((s) => [s.name, formatNumber(s.count, locale), number(s.low), number(s.q1), number(s.median), number(s.q3), number(s.high), s.outliers.map(number).join(\", \")]),\n  };\n  const current = cursor.active === null ? undefined : summaries[cursor.active];\n  const rowsOf = (s: Summary): { label: string; value: string }[] => [\n    { label: labels.high, value: number(s.high) },\n    { label: labels.q3, value: number(s.q3) },\n    { label: labels.median, value: number(s.median) },\n    { label: labels.q1, value: number(s.q1) },\n    { label: labels.low, value: number(s.low) },\n    ...(s.outliers.length > 0 ? [{ label: labels.outliers, value: s.outliers.map(number).join(\", \") }] : []),\n  ];\n\n  return (\n    <div data-slot=\"box-plot\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer\n        aspect={aspect}\n        height={height}\n        table={table}\n        announcement={\n          cursor.keyboard && current\n            ? `${current.name}: ${labels.median} ${number(current.median)}, ${labels.q1} ${number(current.q1)}, ${labels.q3} ${number(current.q3)}, ${labels.low} ${number(current.low)}, ${labels.high} ${number(current.high)}`\n            : \"\"\n        }\n      >\n        {({ width, height: plotHeight }) => {\n          if (summaries.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const top = 10;\n          const bottom = 28;\n          const all = summaries.flatMap((s) => [s.sorted[0] ?? 0, s.sorted[s.sorted.length - 1] ?? 0]);\n          const sy = chartLinear(Math.min(...all), Math.max(...all), [plotHeight - bottom, top]);\n          const axisY = formatValue ?? axisNumberFormatter(Math.max(...all.map(Math.abs)), locale);\n          const left = widestText(sy.ticks.map(axisY)) + 12;\n          const step = (width - left - 8) / summaries.length;\n          const breadth = Math.max(6, Math.min(variant === \"violin\" ? 72 : 40, step * 0.6));\n          const centre = (index: number): number => left + step * (index + 0.5);\n          const [domainLow = 0, domainHigh = 1] = sy.scale.domain();\n          const samples = Array.from({ length: 48 }, (_, i) => domainLow + ((domainHigh - domainLow) * i) / 47);\n          const pad = (domainHigh - domainLow) * 0.05;\n          const spans = summaries.map((s) => (variant === \"violin\" ? samples.filter((p) => p >= (s.sorted[0] ?? 0) - pad && p <= (s.sorted[s.sorted.length - 1] ?? 0) + pad) : []));\n          const shapes = summaries.map((s, index) => (variant === \"violin\" ? density(s.sorted, spans[index] ?? []) : []));\n          const widest = Math.max(1e-12, ...shapes.flat());\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps}>\n                {showGrid ? <ChartGrid offsets={sy.ticks.map((tick) => sy.scale(tick))} from={left} to={width - 8} /> : null}\n                <ChartAxis\n                  side=\"left\"\n                  at={left - 8}\n                  ticks={sy.ticks.map((tick) => ({\n                    offset: sy.scale(tick),\n                    label: axisY(tick),\n                  }))}\n                />\n                <ChartAxis\n                  side=\"bottom\"\n                  at={plotHeight - bottom + 6}\n                  ticks={summaries.map((s, index) => ({\n                    offset: centre(index),\n                    label: fitText(s.name, step - 4),\n                  }))}\n                />\n                <g aria-hidden=\"true\">\n                  {summaries.map((s, index) => {\n                    const style = chartSeries(colorBy === \"group\" ? index : 0);\n                    const cx = centre(index);\n                    const half = breadth / 2;\n                    const dim = cursor.active !== null && cursor.active !== index;\n                    const points = spans[index] ?? [];\n                    const violin =\n                      variant === \"violin\"\n                        ? area<number>()\n                            .curve(curveBasis)\n                            .y((_, i) => sy.scale(points[i] ?? 0))\n                            .x0((d) => cx - (d / widest) * half)\n                            .x1((d) => cx + (d / widest) * half)(shapes[index] ?? [])\n                        : null;\n                    return (\n                      <g key={s.name} className={cn(\"transition-opacity duration-instant motion-reduce:transition-none\", dim && \"opacity-45\")}>\n                        <rect x={cx - step / 2} y={top} width={step} height={plotHeight - bottom - top} fill=\"transparent\" onPointerEnter={() => cursor.point(index)} />\n                        {violin ? <path d={violin} className={cn(style.fill, \"opacity-30\")} /> : null}\n                        <line x1={cx} x2={cx} y1={sy.scale(s.high)} y2={sy.scale(s.q3)} className={style.stroke} strokeWidth={1.5} />\n                        <line x1={cx} x2={cx} y1={sy.scale(s.q1)} y2={sy.scale(s.low)} className={style.stroke} strokeWidth={1.5} />\n                        {variant === \"box\" ? (\n                          <>\n                            <line x1={cx - half / 2} x2={cx + half / 2} y1={sy.scale(s.high)} y2={sy.scale(s.high)} className={style.stroke} strokeWidth={1.5} />\n                            <line x1={cx - half / 2} x2={cx + half / 2} y1={sy.scale(s.low)} y2={sy.scale(s.low)} className={style.stroke} strokeWidth={1.5} />\n                          </>\n                        ) : null}\n                        <rect\n                          x={cx - (variant === \"violin\" ? 5 : half)}\n                          y={sy.scale(s.q3)}\n                          width={variant === \"violin\" ? 10 : breadth}\n                          height={Math.max(1, sy.scale(s.q1) - sy.scale(s.q3))}\n                          className={cn(style.fill, ROUND, style.stroke)}\n                          fillOpacity={variant === \"box\" ? 0.25 : 1}\n                          strokeWidth={1.5}\n                        />\n                        <line\n                          x1={cx - (variant === \"violin\" ? 5 : half)}\n                          x2={cx + (variant === \"violin\" ? 5 : half)}\n                          y1={sy.scale(s.median)}\n                          y2={sy.scale(s.median)}\n                          className={variant === \"violin\" ? \"stroke-background\" : \"stroke-foreground\"}\n                          strokeWidth={2.5}\n                        />\n                        {s.outliers.map((v, i) => (\n                          <circle key={i} cx={cx} cy={sy.scale(v)} r={3} className={cn(\"fill-background\", style.stroke)} strokeWidth={1.5} />\n                        ))}\n                      </g>\n                    );\n                  })}\n                </g>\n              </ChartSvg>\n              {current && cursor.active !== null ? (\n                <ChartTooltip\n                  x={centre(cursor.active) + breadth / 2}\n                  y={sy.scale(current.median)}\n                  side={centre(cursor.active) > width / 2 ? \"left\" : \"right\"}\n                  title={current.name}\n                  rows={rowsOf(current)}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Comparing distributions across groups: which is higher, which is wider, which has outliers. For one group's full shape use histogram; for a few exact numbers per group use bar-chart or dot-plot.",
    "example": "<BoxPlot\n  label=\"Response time by region\"\n  data={[\n    { region: \"North\", ms: 120 }, { region: \"North\", ms: 140 }, { region: \"North\", ms: 135 }, { region: \"North\", ms: 310 },\n    { region: \"South\", ms: 90 }, { region: \"South\", ms: 110 }, { region: \"South\", ms: 105 }, { region: \"South\", ms: 98 },\n  ]}\n  group=\"region\"\n  value=\"ms\"\n  valueLabel=\"Milliseconds\"\n/>",
    "client": true
  }
}
