Box plot
Median, quartiles, whiskers and every outlier per group, with n printed.
The shape of a distribution per group, with median and middle half inside; shows two peaks a box plot hides.
<ViolinPlot />A violin plot draws the distribution of a value for each group as a smooth, mirrored shape. Where the violin is wide, many values sit; where it is thin, few do. Inside, a bar marks the middle half of the values and a dot marks the median.
It shows what a box plot hides. Two groups can have the same median and quartiles while one has a single peak and the other two, such as Enterprise deals that close either in seven weeks or in twenty. The shapes are kernel density estimates cut at the smallest and largest value, so the violin never suggests values that weren't observed. Groups with fewer than eight values are drawn as points instead of a shape, with a note, and every group shows its n.
For the summary alone, a box plot is simpler; for a single group, a histogram.
Violin plot is free under the MIT license.
pnpm dlx shadcn@latest add https://chartslibraryui.com/r/violin-plot.jsonInstalls 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
Building with an AI tool? Download the violin plot for your AI tool and attach it to Claude, ChatGPT, Lovable or Cursor. No terminal needed. How it works
import { ViolinPlot } from "@/components/charts/violin-plot";
import { daysToClose } from "./sample-data";
export function Example() {
return (
<ViolinPlot
title="Enterprise deals close in two waves: around 7 weeks or around 20 weeks"
subtitle="Days from first meeting to closed-won, by segment, last four quarters"
data={daysToClose}
group="segment"
value="days"
format={{ kind: "number", decimals: 0 }}
/>
);
}
One row per observation (long format) with a group key and a numeric value key.
[{ segment: "SMB", days: 21 }, { segment: "Enterprise", days: 138 }, ...]Missing values are null. Invalid values make the chart say what’s wrong instead of drawing a misleading picture. How charts handle bad data
Every chart also accepts the shared frame props: title, subtitle, source, height, mode, toolbar. Common API
export interface ViolinPlotProps extends FrameProps {
/** Raw observations in long format, one row per observation. */
data: Row[];
/** Key of the group (one violin per group) in each row. */
group: string;
/** Key of the numeric observation in each row. */
value: string;
/** Number format for values: "currency", "percent", "integer", "compact" or a format object. */
format?: FormatInput;
/** Draw the median and the middle half (Q1 to Q3) inside each violin. Default true. */
box?: boolean;
/** Show every observation as faint dots on the violin. Default false. */
points?: boolean;
/** Include zero on the value axis. */
zero?: boolean;
}Installs violin-plot.tsx and the shared core/ (12 files).
"use client";
import { useMemo, type PointerEvent } from "react";
import { AXIS_FONT, XGrid } 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 { bandScale, linearScale, valueDomain } from "./core/scale";
import { textWidth, truncate } from "./core/text";
import { useWords } from "./core/words";
export interface ViolinPlotProps extends FrameProps {
/** Raw observations in long format, one row per observation. */
data: Row[];
/** Key of the group (one violin per group) in each row. */
group: string;
/** Key of the numeric observation in each row. */
value: string;
/** Number format for values: "currency", "percent", "integer", "compact" or a format object. */
format?: FormatInput;
/** Draw the median and the middle half (Q1 to Q3) inside each violin. Default true. */
box?: boolean;
/** Show every observation as faint dots on the violin. Default false. */
points?: boolean;
/** Include zero on the value axis. */
zero?: boolean;
}
interface Group {
name: string;
n: number;
min: number;
q1: number;
med: number;
q3: number;
max: number;
values: number[];
/** [value, density 0..1 relative to this group's peak], empty when too few values for a shape */
curve: [number, number][];
}
const SAMPLES = 64;
/** Fewer values than this and the group is drawn as points: a density from a handful of values is invented. */
const MIN_FOR_SHAPE = 8;
/** Gaussian kernel density with Silverman's rule-of-thumb bandwidth, cut at the data range. */
function density(sorted: number[]): [number, number][] {
const n = sorted.length;
const lo = sorted[0];
const hi = sorted[n - 1];
if (hi <= lo) return [];
const mean = sorted.reduce((a, b) => a + b, 0) / n;
const sd = Math.sqrt(sorted.reduce((a, b) => a + (b - mean) ** 2, 0) / Math.max(1, n - 1));
const iqr = quantile(sorted, 0.75) - quantile(sorted, 0.25);
const spread = Math.min(sd || Infinity, iqr / 1.34 || Infinity);
const h = 0.9 * (Number.isFinite(spread) && spread > 0 ? spread : (hi - lo) / 4) * n ** -0.2;
const out: [number, number][] = [];
let peak = 0;
for (let k = 0; k <= SAMPLES; k++) {
const x = lo + ((hi - lo) * k) / SAMPLES;
let d = 0;
for (const v of sorted) d += Math.exp(-0.5 * ((x - v) / h) ** 2);
out.push([x, d]);
if (d > peak) peak = d;
}
return peak > 0 ? out.map(([x, d]) => [x, d / peak] as [number, number]) : [];
}
/**
* The shape of a distribution across groups: each violin is a smoothed density of the values, mirrored, with the
* median and middle half inside. Shows what a box plot hides, such as two peaks. Groups with too few values are
* drawn as points instead of an invented shape.
*/
export function ViolinPlot({ data, group, value, format, box = true, points = false, zero = false, height: hProp, ...frame }: ViolinPlotProps) {
const L = useWords(frame.words);
const { groups, issues } = useMemo(() => {
const issues: Issue[] = [];
if (!Array.isArray(data) || !data.length) return { groups: [] as Group[], issues: [{ level: "error", message: "No data to display." }] as Issue[] };
const map = new Map<string, number[]>();
let invalid = 0;
let missing = 0;
for (const r of data) {
const n = readNum(r?.[value]);
if (n.state === "invalid") invalid++;
else if (n.value === null) missing++;
else {
const g = String(r?.[group] ?? "");
if (!map.has(g)) map.set(g, []);
map.get(g)!.push(n.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.` });
const groups: Group[] = [...map.entries()].map(([name, vals]) => {
const s = [...vals].sort((a, b) => a - b);
return {
name,
n: s.length,
min: s[0],
q1: quantile(s, 0.25),
med: quantile(s, 0.5),
q3: quantile(s, 0.75),
max: s[s.length - 1],
values: s,
curve: s.length >= MIN_FOR_SHAPE ? density(s) : [],
};
});
const small = groups.filter((g) => g.n < MIN_FOR_SHAPE);
if (small.length)
issues.push({
level: "note",
message: `${small.map((g) => g.name).join(", ")} ha${small.length === 1 ? "s" : "ve"} fewer than ${MIN_FOR_SHAPE} values, so ${small.length === 1 ? "it is" : "they are"} drawn as points, not a shape.`,
});
if (groups.length && !invalid) issues.push({ level: "note", message: "Each violin is scaled to its own peak: compare shapes, not widths." });
return { groups, issues };
}, [data, group, value]);
const height = hProp ?? Math.max(160, groups.length * 64 + 30);
const f = (v: unknown) => formatValue(v as number, format, { context: "table" });
const table = {
columns: [
{ key: "name", label: group },
{ key: "n", label: "n", align: "right" as const },
{ key: "min", label: "Min", align: "right" as const, format: f },
{ key: "q1", label: "Q1", align: "right" as const, format: f },
{ key: "med", label: L.median, align: "right" as const, format: f },
{ key: "q3", label: "Q3", align: "right" as const, format: f },
{ key: "max", label: "Max", align: "right" as const, format: f },
],
rows: groups.map(({ name, n, min, q1, med, q3, max }) => ({ name, n, min, q1, med, q3, max })),
};
const summary = `Violin plot of ${groups.length} groups. ${groups
.map((g) => `${g.name}: median ${formatValue(g.med, format)}, middle half ${formatValue(g.q1, format)} to ${formatValue(g.q3, format)}, range ${formatValue(g.min, format)} to ${formatValue(g.max, format)}, n = ${g.n}`)
.join("; ")}.`;
return (
<ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary}>
{({ width }) => <Violins {...{ width, height, groups, format, box, points, zero }} />}
</ChartFrame>
);
}
function Violins({ width, height, groups, format, box, points, zero }: { width: number; height: number; groups: Group[]; format?: FormatInput; box: boolean; points: boolean; zero: boolean }) {
const L = useWords();
const { active, setActive, keyProps } = useActiveIndex(groups.length, { describe: (i) => ({ label: String(groups[i].name) }) });
const labelW = Math.min(Math.max(...groups.map((g) => textWidth(`${g.name}`, AXIS_FONT)), 30) + 14, width * 0.3);
const left = labelW;
const right = width - 14;
const top = 6;
const bottom = height - 22;
const { domain, ticks } = valueDomain(
groups.flatMap((g) => [g.min, g.max]),
{ includeZero: zero, ticks: Math.max(3, Math.floor((right - left) / 90)) },
);
const ft = tickFormatter(format, ticks);
const sx = linearScale(domain, [left, right]);
const band = bandScale(groups.length, [top, bottom], { paddingInner: 0.18, paddingOuter: 0.08 });
const half = Math.min(30, band.bandwidth / 2);
const onMove = (e: PointerEvent<SVGRectElement>) => setActive(band.indexAt(localPoint(e).y + top));
return (
<>
<svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Violin plot. Use arrow keys to read groups." {...keyProps}>
<XGrid ticks={ticks} x={sx} y0={top} y1={bottom} format={ft} labelY={bottom + 16} />
{groups.map((g, i) => {
const cy = band(i) + band.bandwidth / 2;
const shape = g.curve.length
? `M${g.curve.map(([v, d]) => `${sx(v).toFixed(1)},${(cy - d * half).toFixed(1)}`).join("L")}L${[...g.curve]
.reverse()
.map(([v, d]) => `${sx(v).toFixed(1)},${(cy + d * half).toFixed(1)}`)
.join("L")}Z`
: null;
const showPoints = points || !shape;
return (
<g key={g.name} className={`clui-mark${active !== null && active !== i ? " clui-dim" : ""}`}>
<text x={labelW - 10} y={cy - 5} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fill: "var(--clui-ink)" }}>
{truncate(g.name, labelW - 14, AXIS_FONT)}
</text>
<text x={labelW - 10} y={cy + 9} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fontSize: 10 }}>
n = {g.n}
</text>
{shape && <path d={shape} style={{ fill: tokens.series(0), fillOpacity: 0.22, stroke: tokens.series(0) }} strokeWidth={1.5} strokeLinejoin="round" />}
{showPoints &&
g.values.map((v, k) => (
<circle
key={k}
cx={sx(v)}
cy={cy + ((((k * 2654435761) >>> 0) % 100) / 100 - 0.5) * (shape ? half * 0.6 : half * 0.8)}
r={shape ? 1.8 : 3}
style={{ fill: tokens.series(0), opacity: shape ? 0.35 : 0.85 }}
/>
))}
{box && g.n >= 2 && (
<>
<line x1={sx(g.q1)} x2={sx(g.q3)} y1={cy} y2={cy} style={{ stroke: "var(--clui-ink)" }} strokeWidth={5} strokeLinecap="round" />
<circle cx={sx(g.med)} cy={cy} r={3.5} style={{ fill: "var(--clui-surface)", stroke: "var(--clui-ink)" }} strokeWidth={1.5} />
</>
)}
</g>
);
})}
<rect x={0} y={top} width={width} height={Math.max(0, bottom - top)} fill="transparent" onPointerMove={onMove} onPointerLeave={() => setActive(null)} />
</svg>
{active !== null && groups[active] && (
<ChartTooltip
x={sx(groups[active].q3)}
y={band(active) + band.bandwidth / 2}
width={width}
height={height}
data={{
title: `${groups[active].name} (n = ${groups[active].n})`,
rows: [
{ label: "Max", value: formatValue(groups[active].max, format, { context: "tooltip" }) },
{ label: "Q3", value: formatValue(groups[active].q3, format, { context: "tooltip" }) },
{ label: L.median, value: formatValue(groups[active].med, format, { context: "tooltip" }), strong: true },
{ label: "Q1", value: formatValue(groups[active].q1, format, { context: "tooltip" }) },
{ label: "Min", value: formatValue(groups[active].min, format, { context: "tooltip" }) },
],
}}
/>
)}
</>
);
}
Median, quartiles, whiskers and every outlier per group, with n printed.
The shape of one distribution, with automatic binning and a median marker.
Every observation visible by group, with the median marked.