Skip to content
ChartslibraryUI Get Pro

Histogram

The shape of one distribution, with automatic binning and a median marker.

FreeMIT · install in one command<Histogram />

When to use

  • Deal sizes, response times, session lengths
  • Checking skew and long tails

When not to use

Good practice

  • Try a couple of bin counts; the shape can change.
  • Mark the median for skewed data, not the mean.

Installation

Histogram is free under the MIT license.

$ npx shadcn@latest add https://chartslibraryui.com/r/histogram.json

Installs the chart, its dependencies and the shared core into your components folder.

Then import the theme once: import "@/components/charts/core/charts.css" Installation guide

Usage

import { Histogram } from "@/components/charts/histogram";
import { dealSizes } from "./sample-data";

export function Example() {
  return (
    <Histogram
      title="Most deals are under $25K, with a long tail"
      subtitle="Closed-won deal size, last four quarters"
      data={dealSizes}
      format="currency"
      countLabel="Deals"
    />
  );
}

Data

An array of numbers, or rows plus a value key.

[14800, 22100, 9800, ...]

Missing values are null. Invalid values make the chart say what’s wrong instead of drawing a misleading picture. How charts handle bad data

Props

Every chart also accepts the shared frame props: title, subtitle, source, height, mode, toolbar. Common API

export interface HistogramProps extends FrameProps {
  /** Raw observations: numbers, or rows with `value` key. */
  data: (number | null)[] | Row[];
  /** Key of the value when `data` is rows. */
  value?: string;
  /** Number of bins (approximate; edges are rounded). Default: Freedman–Diaconis, clamped to 5–40. */
  bins?: number;
  /** Exact bin width. Overrides `bins`. */
  binWidth?: number;
  format?: FormatInput;
  /** Mark the median or mean. */
  marker?: "median" | "mean" | "none";
  /** Name of what is counted, e.g. "Deals". */
  countLabel?: string;
}

Source

Installs histogram.tsx and the shared core/ (11 files).

View histogram.tsx
"use client";

import { useMemo, type PointerEvent } from "react";
import { XLabels, YGrid, axisWidth } from "./core/axis";
import { color as tokens } from "./core/color";
import { quantile, readNum, type Issue, type Row } from "./core/data";
import { formatValue, tickFormatter, type FormatInput } from "./core/format";
import { ChartFrame, ChartTooltip, localPoint, useActiveIndex, type FrameProps } from "./core/frame";
import { barPath } from "./core/path";
import { linearScale, niceTicks, valueDomain } from "./core/scale";

export interface HistogramProps extends FrameProps {
  /** Raw observations: numbers, or rows with `value` key. */
  data: (number | null)[] | Row[];
  /** Key of the value when `data` is rows. */
  value?: string;
  /** Number of bins (approximate; edges are rounded). Default: Freedman–Diaconis, clamped to 5–40. */
  bins?: number;
  /** Exact bin width. Overrides `bins`. */
  binWidth?: number;
  format?: FormatInput;
  /** Mark the median or mean. */
  marker?: "median" | "mean" | "none";
  /** Name of what is counted, e.g. "Deals". */
  countLabel?: string;
}

interface Bin {
  x0: number;
  x1: number;
  count: number;
}

export function binValues(values: number[], opts: { bins?: number; binWidth?: number }): Bin[] {
  if (!values.length) return [];
  const sorted = [...values].sort((a, b) => a - b);
  const lo = sorted[0];
  const hi = sorted[sorted.length - 1];
  let width = opts.binWidth;
  if (!width) {
    let n = opts.bins;
    if (!n) {
      const iqr = quantile(sorted, 0.75) - quantile(sorted, 0.25);
      const fd = iqr > 0 ? (2 * iqr) / Math.cbrt(sorted.length) : 0;
      n = fd > 0 ? Math.ceil((hi - lo) / fd) : Math.ceil(Math.log2(sorted.length) + 1);
      n = Math.max(5, Math.min(40, n));
    }
    const ticks = niceTicks(lo, hi === lo ? lo + 1 : hi, n);
    width = ticks.length > 1 ? ticks[1] - ticks[0] : 1;
  }
  const start = Math.floor(lo / width) * width;
  const count = Math.max(1, Math.ceil((hi - start) / width + 1e-9) + (hi === start ? 1 : 0));
  const bins: Bin[] = Array.from({ length: count }, (_, i) => ({ x0: start + i * width!, x1: start + (i + 1) * width!, count: 0 }));
  for (const v of values) {
    let i = Math.floor((v - start) / width);
    if (i >= count) i = count - 1;
    if (i < 0) i = 0;
    bins[i].count++;
  }
  return bins;
}

/**
 * The shape of one distribution: where values cluster, how spread they are, whether there is a long tail.
 * Needs at least ~30 observations to say anything; for fewer, show the points (strip plot).
 */
export function Histogram({ data, value, bins: binCount, binWidth, format, marker = "median", countLabel = "Count", height = 260, ...frame }: HistogramProps) {
  const { values, issues } = useMemo(() => {
    const issues: Issue[] = [];
    const raw: unknown[] = Array.isArray(data) ? data.map((d) => (typeof d === "object" && d !== null ? (d as Row)[value ?? "value"] : d)) : [];
    if (!raw.length) return { values: [] as number[], issues: [{ level: "error", message: "No data to display." }] as Issue[] };
    let missing = 0;
    let invalid = 0;
    const values: number[] = [];
    for (const v of raw) {
      const r = readNum(v);
      if (r.state === "missing") missing++;
      else if (r.state === "invalid") invalid++;
      else values.push(r.value!);
    }
    if (invalid) issues.push({ level: "error", message: `${invalid} value(s) are not numbers.` });
    if (missing) issues.push({ level: "note", message: `${missing} missing value(s) are not counted.` });
    if (!values.length && !invalid) issues.push({ level: "error", message: "No values to bin." });
    else if (values.length < 20) issues.push({ level: "warning", message: `Only ${values.length} observations; a histogram's shape is unreliable this small.` });
    return { values, issues };
  }, [data, value]);

  const bins = useMemo(() => binValues(values, { bins: binCount, binWidth }), [values, binCount, binWidth]);
  const sorted = useMemo(() => [...values].sort((a, b) => a - b), [values]);
  const mark = marker === "none" || !values.length ? null : marker === "mean" ? values.reduce((a, b) => a + b, 0) / values.length : quantile(sorted, 0.5);

  const table = {
    columns: [
      { key: "range", label: "Range" },
      { key: "count", label: countLabel, align: "right" as const },
    ],
    rows: bins.map((b) => ({ range: `${formatValue(b.x0, format, { context: "table" })} – ${formatValue(b.x1, format, { context: "table" })}`, count: b.count })),
  };
  const peak = bins.reduce((a, b) => (b.count > a.count ? b : a), bins[0] ?? { x0: 0, x1: 0, count: 0 });
  const summary = `Histogram of ${values.length} values in ${bins.length} bins. Most common range ${formatValue(peak.x0, format)} to ${formatValue(
    peak.x1,
    format,
  )} (${peak.count}).${mark !== null ? ` ${marker} ${formatValue(mark, format)}.` : ""}`;

  return (
    <ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary}>
      {({ width }) => <HistPlot width={width} height={height} bins={bins} format={format} mark={mark} markLabel={marker} countLabel={countLabel} />}
    </ChartFrame>
  );
}

function HistPlot({ width, height, bins, format, mark, markLabel, countLabel }: { width: number; height: number; bins: Bin[]; format?: FormatInput; mark: number | null; markLabel: string; countLabel: string }) {
  const { active, setActive, keyProps } = useActiveIndex(bins.length);
  const { domain, ticks } = valueDomain(bins.map((b) => b.count), { includeZero: true, ticks: Math.max(2, Math.floor(height / 55)) });
  const fy = tickFormatter("integer", ticks);
  const left = axisWidth(ticks.map(fy));
  const right = width - 8;
  const top = 18;
  const bottom = height - 24;
  const x0 = bins[0]?.x0 ?? 0;
  const x1 = bins[bins.length - 1]?.x1 ?? 1;
  const sx = linearScale([x0, x1], [left, right]);
  const sy = linearScale(domain, [bottom, top]);
  const edges = [...bins.map((b) => b.x0), x1];
  const edgeFmt = tickFormatter(format, edges);
  const onMove = (e: PointerEvent<SVGRectElement>) => {
    const v = sx.invert(localPoint(e).x + left);
    setActive(Math.max(0, Math.min(bins.length - 1, bins.findIndex((b) => v >= b.x0 && v < b.x1) === -1 ? bins.length - 1 : bins.findIndex((b) => v >= b.x0 && v < b.x1))));
  };
  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Histogram. Use arrow keys to read bins." {...keyProps}>
        <YGrid ticks={ticks} y={sy} x0={left} x1={right} format={fy} />
        <XLabels positions={edges.map((e) => sx(e))} labels={edges.map(edgeFmt)} y={bottom + 17} anchorEnds x0={left - 8} x1={width} />
        {bins.map((b, i) => {
          const bx = sx(b.x0) + 1;
          const w = Math.max(1, sx(b.x1) - sx(b.x0) - 2);
          const by = sy(b.count);
          return (
            <path
              key={i}
              d={barPath(bx, by, w, Math.max(0, bottom - by), 3, "up")}
              style={{ fill: tokens.series(0) }}
              className={`clui-mark${active !== null && active !== i ? " clui-dim" : ""}`}
            />
          );
        })}
        {mark !== null && (
          <g aria-hidden>
            <line x1={sx(mark)} x2={sx(mark)} y1={top - 6} y2={bottom} style={{ stroke: "var(--clui-ink)" }} strokeWidth={1.25} strokeDasharray="3 3" />
            <text x={sx(mark) + 5} y={top - 6} className="clui-annot clui-halo">
              {markLabel === "mean" ? "Mean" : "Median"} {formatValue(mark, format)}
            </text>
          </g>
        )}
        <rect x={left} y={0} width={Math.max(0, right - left)} height={bottom} fill="transparent" onPointerMove={onMove} onPointerLeave={() => setActive(null)} />
      </svg>
      {active !== null && bins[active] && (
        <ChartTooltip
          x={sx((bins[active].x0 + bins[active].x1) / 2)}
          y={sy(bins[active].count)}
          width={width}
          height={height}
          data={{
            title: `${formatValue(bins[active].x0, format, { context: "tooltip" })} – ${formatValue(bins[active].x1, format, { context: "tooltip" })}`,
            rows: [{ label: countLabel, value: formatValue(bins[active].count, "integer") }],
          }}
        />
      )}
    </>
  );
}
Pro

Box plot

Median, quartiles, whiskers and every outlier per group, with n printed.

Strip plot

Every observation visible by group, with the median marked.

Scatter chart

The relationship between two measures, with groups, bubbles, quadrants and a trend line.