Chart
Bar, line, area and pie charts drawn with the pen. One ink, so series are told apart by how they are coloured in: shaded, hatched, cross-hatched or dotted. No charting library.
- Desktop
- Mobile
| month | Desktop | Mobile |
|---|---|---|
| Jan | 186 | 80 |
| Feb | 305 | 200 |
| Mar | 237 | 120 |
| Apr | 173 | 190 |
| May | 209 | 130 |
| Jun | 214 | 140 |
import { BarChart, ChartContainer, type ChartConfig } from "@/components/ui/chart";
const data = [
{ month: "Jan", desktop: 186, mobile: 80 },
{ month: "Feb", desktop: 305, mobile: 200 },
{ month: "Mar", desktop: 237, mobile: 120 },
{ month: "Apr", desktop: 173, mobile: 190 },
{ month: "May", desktop: 209, mobile: 130 },
{ month: "Jun", desktop: 214, mobile: 140 },
];
const config = {
desktop: { label: "Desktop" },
mobile: { label: "Mobile" },
} satisfies ChartConfig;
export default function ChartDemo() {
return (
<ChartContainer config={config} className="h-72 w-full max-w-xl">
<BarChart data={data} xKey="month" label="Visitors by month, desktop and mobile" seed="chart-demo" />
</ChartContainer>
);
}Installation
pnpm dlx shadcn@latest add @ballpoint/ chart"use client";
import { createContext, useContext, useId, useMemo, useState, type ComponentProps, type PointerEvent, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { penStyle, useInkBox, useInkSeed, usePen, type Pen } from "@/hooks/use-ink-box";
import { InkSvg, Stroke } from "@/lib/ink";
import { InkPanel } from "@/lib/ink-panel";
import { dotStroke, handCurve, lineStroke, penBoxStrokes } from "@/lib/ink-sketch";
// Charts drawn with the pen. Everything is one ink, so what tells one series
// from another is how it is coloured in: shaded solid, hatched, cross-hatched
// or dotted, at a lighter or heavier pressure. No charting library: the data
// goes straight to strokes, and each chart carries a hidden table of its data
// for screen readers.
export type ChartFill = "shade" | "hatch" | "cross" | "dots" | "plain";
export type ChartConfig = Record<
string,
{
/** What the series is called in the legend and the tooltip. */
label?: string;
/** How it is coloured in. By default each series takes the next style in turn. */
fill?: ChartFill;
/** The pressure of the pen: the full ink, or lighter. */
tone?: "ink" | "ink-2" | "ink-3";
}
>;
const fillOrder: ChartFill[] = ["shade", "hatch", "cross", "dots"];
const toneOrder = ["ink", "ink-2", "ink-3", "ink-3"] as const;
const toneClass = { ink: "text-ink", "ink-2": "text-ink-2", "ink-3": "text-ink-3" } as const;
const ChartContext = createContext<{ config: ChartConfig; uid: string }>({ config: {}, uid: "" });
/** Where a series sits in the config decides its style, and its label and tone if it gives none. */
function styleOf(config: ChartConfig, key: string, index: number) {
const entry = config[key] ?? {};
return { label: entry.label ?? key, fill: entry.fill ?? fillOrder[index % fillOrder.length], tone: entry.tone ?? toneOrder[index % toneOrder.length] };
}
/** The frame for a chart: give it a height (`h-72`) and a config naming the series. */
function ChartContainer({ config, className, children, ...props }: ComponentProps<"div"> & { config: ChartConfig }) {
const uid = useId().replace(/[^\w-]/g, "");
const value = useMemo(() => ({ config, uid }), [config, uid]);
return (
<ChartContext value={value}>
<div data-slot="chart" className={cn("relative flex h-72 w-full flex-col gap-3 text-base", className)} {...props}>
{children}
</div>
</ChartContext>
);
}
const numbers = new Intl.NumberFormat("en-US");
/** A tidy top for the axis and the steps up to it: 1, 2 or 5 times a power of ten. */
function niceTicks(max: number, target = 4) {
if (!(max > 0)) return [0, 1];
const raw = max / target;
const pow = 10 ** Math.floor(Math.log10(raw));
const step = ([1, 2, 5, 10].find((m) => m * pow >= raw) ?? 10) * pow;
const ticks: number[] = [];
for (let v = 0; v <= max + step * 0.999; v += step) ticks.push(+v.toFixed(10));
return ticks;
}
/** The hatching a series is coloured in with, as an SVG pattern that takes the series' ink. */
function FillDefs({ id, fill }: { id: string; fill: ChartFill }) {
if (fill === "plain") return null;
return (
<pattern id={id} patternUnits="userSpaceOnUse" width={fill === "shade" ? 2.6 : 5} height={fill === "shade" ? 2.6 : 5} patternTransform={fill === "dots" ? undefined : "rotate(-45)"}>
{fill === "shade" && <path d="M0 -1V4" style={{ stroke: "currentColor", strokeWidth: 1.5, fill: "none" }} />}
{fill === "hatch" && <path d="M0 -1V6" style={{ stroke: "currentColor", strokeWidth: 1, fill: "none" }} />}
{fill === "cross" && <path d="M0 -1V6M-1 2.5H6" style={{ stroke: "currentColor", strokeWidth: 0.9, fill: "none" }} />}
{fill === "dots" && <circle cx={2.5} cy={2.5} r={1.1} style={{ fill: "currentColor" }} />}
</pattern>
);
}
/** A small square of a series' style, for legends and tooltips. */
function Swatch({ fill, tone, className }: { fill: ChartFill; tone: keyof typeof toneClass; className?: string }) {
const id = `swatch-${useId().replace(/[^\w-]/g, "")}`;
return (
<svg aria-hidden="true" viewBox="0 0 14 14" className={cn("size-3.5 shrink-0", toneClass[tone], className)}>
<defs>
<FillDefs id={id} fill={fill} />
</defs>
<rect x={1} y={1} width={12} height={12} rx={2} fill={fill === "plain" ? "none" : `url(#${id})`} stroke="currentColor" strokeWidth={1.2} />
</svg>
);
}
/** The key to a chart's series, one swatch and name each. */
function ChartLegendContent({ keys, className }: { keys?: string[]; className?: string }) {
const { config } = useContext(ChartContext);
const list = keys ?? Object.keys(config);
return (
<ul data-slot="chart-legend" className={cn("flex flex-wrap items-center justify-center gap-x-5 gap-y-1 text-sm text-ink-2", className)}>
{list.map((key, i) => {
const style = styleOf(config, key, i);
return (
<li key={key} className="flex items-center gap-1.5">
<Swatch fill={style.fill} tone={style.tone} />
{style.label}
</li>
);
})}
</ul>
);
}
/** What the tooltip says: a heading and a line for each value. */
function ChartTooltipContent({ title, rows, className }: { title?: ReactNode; rows: { key: string; value: ReactNode; index: number }[]; className?: string }) {
const { config } = useContext(ChartContext);
return (
<div data-slot="chart-tooltip" className={cn("flex min-w-32 flex-col gap-1 text-sm", className)}>
{title && <div className="font-bold text-ink">{title}</div>}
{rows.map(({ key, value, index }) => {
const style = styleOf(config, key, index);
return (
<div key={key} className="flex items-center gap-2 text-ink-2">
<Swatch fill={style.fill} tone={style.tone} />
<span>{style.label}</span>
<span className="ml-auto pl-3 font-bold text-ink tabular-nums">{value}</span>
</div>
);
})}
</div>
);
}
type Hover = { index: number; x: number; y: number } | null;
/** A paper tooltip held near the pointer, kept inside the chart. */
function Tooltip({ hover, width, children, seed }: { hover: Hover; width: number; children: ReactNode; seed?: string | number }) {
const pen = usePen({ draw: "mount" });
if (!hover) return null;
const flip = hover.x > width * 0.6;
return (
<div
aria-hidden="true"
className="ink-paper pointer-events-none absolute z-10 isolate px-3 py-2"
style={{ left: hover.x, top: Math.max(hover.y - 8, 0), transform: `translate(${flip ? "calc(-100% - 14px)" : "14px"}, 0)` }}
>
<InkPanel pen={pen} seed={seed} estimate={[160, 70]} offset={4} maxRadius={10} className="text-ink-3" />
{children}
</div>
);
}
type CartesianProps = {
data: Record<string, string | number>[];
/** The key in each row that names it along the bottom. */
xKey: string;
/** Which keys of each row to plot. By default, every key in the chart's config. */
series?: string[];
/** Writes a value on the axis and in the tooltip. */
format?: (value: number) => string;
/** A name for the chart, for screen readers. */
label?: string;
tooltip?: boolean;
legend?: boolean;
seed?: string | number;
} & Pick<Pen, "roughness" | "draw" | "weight" | "speed">;
const margin = { top: 12, right: 12, bottom: 30, left: 12 };
/** The axes, gridlines and tick labels every cartesian chart shares. */
function useCartesian(props: CartesianProps, stacked: boolean) {
const { config } = useContext(ChartContext);
const { data, series, format = (v: number) => numbers.format(v) } = props;
const keys = series ?? Object.keys(config);
const max = Math.max(...data.map((row) => (stacked ? keys.reduce((sum, key) => sum + (Number(row[key]) || 0), 0) : Math.max(...keys.map((key) => Number(row[key]) || 0)))), 0);
const ticks = niceTicks(max);
const top = ticks[ticks.length - 1];
const left = margin.left + Math.max(...ticks.map((t) => format(t).length)) * 7.5 + 8;
return { config, keys, ticks, top, left, format };
}
function Plot({
props,
stacked = false,
children,
}: {
props: CartesianProps;
stacked?: boolean;
children: (g: { w: number; h: number; pw: number; ph: number; left: number; band: number; y: (v: number) => number; keys: string[]; uid: string; s: number; rough: number; mode: NonNullable<Pen["draw"]>; hover: Hover }) => ReactNode;
}) {
const { data, xKey, label, tooltip = true, legend = true, seed, roughness, draw, weight, speed } = props;
const { config, uid } = useContext(ChartContext);
const pen = usePen({ roughness, draw, weight, speed });
const s = useInkSeed(seed);
const [ref, [w, h]] = useInkBox([480, 240], { step: 4 });
const { keys, ticks, top, left, format } = useCartesian(props, stacked);
const [hover, setHover] = useState<Hover>(null);
if (!data.length) return null;
const pw = Math.max(w - left - margin.right, 10);
const ph = Math.max(h - margin.top - margin.bottom, 10);
const band = pw / data.length;
const y = (v: number) => margin.top + ph - (v / top) * ph;
const rough = pen.roughness ?? 1;
const mode = pen.draw ?? "auto";
const labelEvery = Math.max(1, Math.ceil((Math.max(...data.map((row) => String(row[xKey]).length)) * 8 + 8) / band));
const move = (event: PointerEvent<SVGRectElement>) => {
const box = event.currentTarget.ownerSVGElement?.getBoundingClientRect();
if (!box) return;
const px = event.clientX - box.left;
const index = Math.min(data.length - 1, Math.max(0, Math.floor((px - left) / band)));
setHover({ index, x: left + band * (index + 0.5), y: event.clientY - box.top });
};
return (
<>
<div className="relative min-h-0 flex-1">
<InkSvg ref={ref} pending={mode === "auto"} box={[0, 0, w, h]} stretch className="inset-0 size-full" style={penStyle(pen)}>
<defs>
{keys.map((key, i) => (
<FillDefs key={key} id={`${uid}-fill-${i}`} fill={styleOf(config, key, i).fill} />
))}
</defs>
{/* The gridlines, ruled lightly, and the axis they stand on. */}
{ticks.map((t, i) => (
<g key={t}>
<Stroke d={lineStroke(s + 100 + i, [left, y(t)], [left + pw, y(t)], { bow: 0.6 * rough, jitter: 0.3 * rough })} draw={mode} delay={i * 60} duration={500} width={i === 0 ? 1.4 : 0.8} opacity={i === 0 ? 0.9 : 0.28} className="text-ink-3" />
<text x={left - 8} y={y(t)} textAnchor="end" dominantBaseline="middle" className="fill-ink-3 text-sm">
{format(t)}
</text>
</g>
))}
{data.map((row, i) =>
i % labelEvery ? null : (
<text key={i} x={left + band * (i + 0.5)} y={margin.top + ph + 20} textAnchor="middle" className="fill-ink-3 text-sm">
{String(row[xKey])}
</text>
),
)}
{children({ w, h, pw, ph, left, band, y, keys, uid, s, rough, mode, hover })}
{tooltip && (
<rect
x={left}
y={margin.top}
width={pw}
height={ph}
fill="transparent"
style={{ pointerEvents: "all" }}
onPointerMove={move}
onPointerLeave={() => setHover(null)}
/>
)}
</InkSvg>
{tooltip && (
<Tooltip hover={hover} width={w} seed={`${seed ?? uid}-tip`}>
{hover && (
<ChartTooltipContent
title={String(data[hover.index][xKey])}
rows={keys.map((key, index) => ({ key, index, value: format(Number(data[hover.index][key]) || 0) }))}
/>
)}
</Tooltip>
)}
</div>
{legend && keys.length > 1 && <ChartLegendContent keys={keys} />}
{label && (
<table className="sr-only">
<caption>{label}</caption>
<thead>
<tr>
<th scope="col">{xKey}</th>
{keys.map((key, i) => (
<th key={key} scope="col">
{styleOf(config, key, i).label}
</th>
))}
</tr>
</thead>
<tbody>
{data.map((row, i) => (
<tr key={i}>
<th scope="row">{String(row[xKey])}</th>
{keys.map((key) => (
<td key={key}>{String(row[key])}</td>
))}
</tr>
))}
</tbody>
</table>
)}
</>
);
}
/**
* Bars drawn with the pen and coloured in by hand, one group a row of data.
* `stacked` piles a row's series on top of each other.
*/
function BarChart(props: CartesianProps & { stacked?: boolean }) {
const { stacked = false } = props;
const { data } = props;
const { config } = useContext(ChartContext);
return (
<Plot props={props} stacked={stacked}>
{({ band, y, left, keys, uid, s, rough, mode, hover }) => {
const groupWidth = band * 0.72;
const barWidth = stacked ? groupWidth : groupWidth / keys.length;
return (
<>
{hover && <rect x={left + band * hover.index} y={margin.top} width={band} height={Math.max(y(0) - margin.top, 0)} className="fill-ink-5" opacity={0.5} />}
{data.map((row, i) => {
let base = 0;
return keys.map((key, k) => {
const value = Number(row[key]) || 0;
const style = styleOf(config, key, k);
const x = left + band * i + (band - groupWidth) / 2 + (stacked ? 0 : k * barWidth);
const from = stacked ? base : 0;
if (stacked) base += value;
const y1 = y(from + value);
const y0 = y(from);
const bw = Math.max(barWidth - (stacked ? 0 : 3), 2);
const bh = Math.max(y0 - y1, 0);
if (bh < 0.5) return null;
return (
<g key={`${i}-${key}`} transform={`translate(${x + (stacked ? 0 : 1.5)} ${y1})`} className={toneClass[style.tone]}>
{style.fill !== "plain" && <rect width={bw} height={bh} fill={`url(#${uid}-fill-${k})`} opacity={0.9} />}
{penBoxStrokes(s + i * 7 + k, bw, bh, { roughness: rough, passes: 1, corners: "joined" }).map((d, p) => (
<Stroke key={p} d={d} draw={mode} delay={120 + i * 50 + k * 80} duration={420} width={1.3} />
))}
</g>
);
});
})}
</>
);
}}
</Plot>
);
}
type LineProps = CartesianProps & {
/** A hand-smoothed line, or straight pulls between the points. */
curve?: "natural" | "linear";
/** Mark each point with a ring. */
dots?: boolean;
};
function LinePlot(props: LineProps & { area?: boolean }) {
const { curve = props.area ? "linear" : "natural", dots = true, area = false, data } = props;
const { config } = useContext(ChartContext);
return (
<Plot props={props}>
{({ band, y, left, keys, uid, s, rough, mode, hover, ph }) => {
const bottom = margin.top + ph;
return (
<>
{hover && <Stroke d={lineStroke(s + 900, [hover.x, margin.top], [hover.x, bottom], { bow: 0.3, jitter: 0.2 })} draw="none" width={0.9} opacity={0.5} className="text-ink-3" />}
{keys.map((key, k) => {
const style = styleOf(config, key, k);
const pts = data.map((row, i) => [left + band * (i + 0.5), y(Number(row[key]) || 0)] as [number, number]);
if (pts.length < 2) return null;
const d =
curve === "natural"
? handCurve(s + k, pts, { jitter: 0.25 * rough })
: pts
.slice(1)
.map((p, i) => {
const leg = lineStroke(s + k * 31 + i, pts[i], p, { bow: 0.4 * rough, jitter: 0.2 * rough });
return i === 0 ? leg : leg.replace(/^M[^C]*/, "");
})
.join("");
const fillPath = `M${pts[0][0]} ${bottom}L${pts.map((p) => `${p[0]} ${p[1]}`).join("L")}L${pts[pts.length - 1][0]} ${bottom}Z`;
return (
<g key={key} className={toneClass[style.tone]}>
{area && style.fill !== "plain" && <path d={fillPath} opacity={0.55} style={{ fill: `url(#${uid}-fill-${k})`, stroke: "none" }} />}
<Stroke d={d} draw={mode} delay={150 + k * 200} duration={900} width={k === 0 ? 1.8 : 1.4} />
{dots &&
pts.map(([px, py], i) => (
<g key={i} transform={`translate(${px} ${py})`}>
<circle r={hover?.index === i ? 5 : 3.2} className="fill-paper" style={{ stroke: "none" }} />
<Stroke d={dotStroke(s + 500 + i + k * 40, hover?.index === i ? 4.4 : 2.6)} draw={mode} delay={500 + i * 40} duration={220} width={1.4} />
</g>
))}
</g>
);
})}
</>
);
}}
</Plot>
);
}
/** A line drawn through each series by hand. */
function LineChart(props: LineProps) {
return <LinePlot {...props} />;
}
/** The same lines with the ground under them coloured in. */
function AreaChart(props: LineProps) {
return <LinePlot {...props} area />;
}
/**
* A pie, or a ring with `innerRadius` set. Each slice is outlined with the
* pen and coloured in with the next style; `children` go in the middle of a ring.
*/
function PieChart({
data,
nameKey = "name",
valueKey = "value",
innerRadius = 0.55,
format = (v: number) => numbers.format(v),
label,
tooltip = true,
legend = true,
seed,
roughness,
draw,
weight,
speed,
children,
}: {
data: Record<string, string | number>[];
nameKey?: string;
valueKey?: string;
/** 0 for a whole pie, up to 0.9 for a thin ring. */
innerRadius?: number;
format?: (value: number) => string;
label?: string;
tooltip?: boolean;
legend?: boolean;
seed?: string | number;
children?: ReactNode;
} & Pick<Pen, "roughness" | "draw" | "weight" | "speed">) {
const { config, uid } = useContext(ChartContext);
const pen = usePen({ roughness, draw, weight, speed });
const s = useInkSeed(seed);
const [ref, [w, h]] = useInkBox([240, 240], { step: 4 });
const [hover, setHover] = useState<Hover>(null);
const total = data.reduce((sum, row) => sum + (Number(row[valueKey]) || 0), 0);
const rough = pen.roughness ?? 1;
const mode = pen.draw ?? "auto";
const cx = w / 2;
const cy = h / 2;
const outer = Math.max(Math.min(w, h) / 2 - 6, 10);
const inner = outer * Math.min(Math.max(innerRadius, 0), 0.92);
const slices = useMemo(() => {
const values = data.map((row) => Number(row[valueKey]) || 0);
return data.map((row, i) => {
const value = values[i];
const sweep = total ? (value / total) * Math.PI * 2 : 0;
const a0 = -Math.PI / 2 + (total ? (values.slice(0, i).reduce((sum, v) => sum + v, 0) / total) * Math.PI * 2 : 0);
const steps = Math.max(2, Math.ceil(sweep / 0.2));
const arc = (r: number, from: number, to: number) => Array.from({ length: steps + 1 }, (_, k) => [cx + Math.cos(from + ((to - from) * k) / steps) * r, cy + Math.sin(from + ((to - from) * k) / steps) * r] as [number, number]);
const ring = [...arc(outer, a0, a0 + sweep), ...(inner > 0 ? arc(inner, a0 + sweep, a0) : [[cx, cy] as [number, number]])];
const fillPath = `M${ring.map((p) => `${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join("L")}Z`;
// Drawn as the pen would: the outer edge and the inner edge as curves, and
// the edge where the slice starts as one straight line. (A smoothed loop
// round the whole slice puts a loop in every corner.)
const whole = sweep > Math.PI * 2 - 0.01;
const at = (r: number, a: number): [number, number] => [cx + Math.cos(a) * r, cy + Math.sin(a) * r];
const jitter = 0.3 * rough;
const seedAt = s + i * 4;
const strokes = [
handCurve(seedAt, arc(outer, a0, a0 + sweep), { jitter, closed: whole }),
...(inner > 0 ? [handCurve(seedAt + 1, arc(inner, a0, a0 + sweep), { jitter, closed: whole })] : []),
...(whole || !total ? [] : [lineStroke(seedAt + 2, at(inner > 0 ? inner : 0, a0), at(outer, a0), { bow: 0.4 * rough, jitter, overshoot: 1 })]),
];
return { i, key: String(row[nameKey]), value, mid: a0 + sweep / 2, fillPath, strokes };
});
}, [data, valueKey, nameKey, total, cx, cy, outer, inner, rough, s]);
if (!data.length) return null;
const tones = (i: number) => styleOf(config, String(data[i][nameKey]), i);
const move = (index: number) => (event: PointerEvent<SVGGElement>) => {
const box = event.currentTarget.ownerSVGElement?.getBoundingClientRect();
if (box) setHover({ index, x: event.clientX - box.left, y: event.clientY - box.top });
};
return (
<>
<div className="relative min-h-0 flex-1">
<InkSvg ref={ref} pending={mode === "auto"} box={[0, 0, w, h]} stretch className="inset-0 size-full" style={penStyle(pen)}>
<defs>
{data.map((row, i) => (
<FillDefs key={i} id={`${uid}-fill-${i}`} fill={tones(i).fill} />
))}
</defs>
{slices.map((slice) => {
const style = tones(slice.i);
const lifted = hover?.index === slice.i;
const out = lifted ? 5 : 0;
return (
<g
key={slice.i}
className={toneClass[style.tone]}
transform={`translate(${Math.cos(slice.mid) * out} ${Math.sin(slice.mid) * out})`}
style={{ transition: "transform 160ms ease-out" }}
onPointerMove={tooltip ? move(slice.i) : undefined}
onPointerLeave={() => setHover(null)}
>
{style.fill !== "plain" && <path d={slice.fillPath} opacity={0.85} style={{ fill: `url(#${uid}-fill-${slice.i})`, stroke: "none", pointerEvents: "all" }} />}
{slice.strokes.map((d, k) => (
<Stroke key={k} d={d} draw={mode} delay={slice.i * 140 + k * 90} duration={k === 2 ? 220 : 560} width={1.5} />
))}
</g>
);
})}
</InkSvg>
{children && <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center text-center">{children}</div>}
{tooltip && (
<Tooltip hover={hover} width={w} seed={`${seed ?? uid}-tip`}>
{hover && <ChartTooltipContent rows={[{ key: String(data[hover.index][nameKey]), index: hover.index, value: `${format(slices[hover.index].value)} · ${total ? Math.round((slices[hover.index].value / total) * 100) : 0}%` }]} />}
</Tooltip>
)}
</div>
{legend && <ChartLegendContent keys={data.map((row) => String(row[nameKey]))} />}
{label && (
<table className="sr-only">
<caption>{label}</caption>
<tbody>
{data.map((row, i) => (
<tr key={i}>
<th scope="row">{String(row[nameKey])}</th>
<td>{String(row[valueKey])}</td>
</tr>
))}
</tbody>
</table>
)}
</>
);
}
export { ChartContainer, BarChart, LineChart, AreaChart, PieChart, ChartLegendContent, ChartTooltipContent };Usage
import { BarChart, ChartContainer, type ChartConfig } from "@/components/ui/chart"
const config = {
desktop: { label: "Desktop" },
mobile: { label: "Mobile" },
} satisfies ChartConfig
<ChartContainer config={config} className="h-72 w-full">
<BarChart data={data} xKey="month" label="Visitors by month" />
</ChartContainer>Examples
Stacked bars
A row's series piled on top of one another.
- Sketches
- Letters
- Lists
| day | Sketches | Letters | Lists |
|---|---|---|---|
| Mon | 12 | 6 | 3 |
| Tue | 9 | 8 | 5 |
| Wed | 15 | 4 | 2 |
| Thu | 7 | 10 | 6 |
| Fri | 11 | 5 | 4 |
import { BarChart, ChartContainer, type ChartConfig } from "@/components/ui/chart";
const data = [
{ day: "Mon", sketches: 12, letters: 6, lists: 3 },
{ day: "Tue", sketches: 9, letters: 8, lists: 5 },
{ day: "Wed", sketches: 15, letters: 4, lists: 2 },
{ day: "Thu", sketches: 7, letters: 10, lists: 6 },
{ day: "Fri", sketches: 11, letters: 5, lists: 4 },
];
const config = {
sketches: { label: "Sketches" },
letters: { label: "Letters" },
lists: { label: "Lists" },
} satisfies ChartConfig;
export default function ChartStacked() {
return (
<ChartContainer config={config} className="h-72 w-full max-w-xl">
<BarChart data={data} xKey="day" stacked label="Pages written each day, by kind" seed="chart-stacked" />
</ChartContainer>
);
}Lines
A hand-smoothed line for each series, with a ring at every point.
- Ink
- Pencil
| month | Ink | Pencil |
|---|---|---|
| Jan | 120 | 40 |
| Feb | 180 | 55 |
| Mar | 160 | 90 |
| Apr | 240 | 70 |
| May | 210 | 130 |
| Jun | 290 | 110 |
import { ChartContainer, LineChart, type ChartConfig } from "@/components/ui/chart";
const data = [
{ month: "Jan", ink: 120, pencil: 40 },
{ month: "Feb", ink: 180, pencil: 55 },
{ month: "Mar", ink: 160, pencil: 90 },
{ month: "Apr", ink: 240, pencil: 70 },
{ month: "May", ink: 210, pencil: 130 },
{ month: "Jun", ink: 290, pencil: 110 },
];
const config = {
ink: { label: "Ink" },
pencil: { label: "Pencil", tone: "ink-3" },
} satisfies ChartConfig;
export default function ChartLine() {
return (
<ChartContainer config={config} className="h-72 w-full max-w-xl">
<LineChart data={data} xKey="month" label="Pages by month, in ink and in pencil" seed="chart-line" />
</ChartContainer>
);
}Area
A line with the ground under it hatched in.
| week | Pages |
|---|---|
| W1 | 14 |
| W2 | 22 |
| W3 | 19 |
| W4 | 31 |
| W5 | 27 |
| W6 | 38 |
| W7 | 34 |
import { AreaChart, ChartContainer, type ChartConfig } from "@/components/ui/chart";
const data = [
{ week: "W1", pages: 14 },
{ week: "W2", pages: 22 },
{ week: "W3", pages: 19 },
{ week: "W4", pages: 31 },
{ week: "W5", pages: 27 },
{ week: "W6", pages: 38 },
{ week: "W7", pages: 34 },
];
const config = { pages: { label: "Pages", fill: "hatch" } } satisfies ChartConfig;
export default function ChartArea() {
return (
<ChartContainer config={config} className="h-72 w-full max-w-xl">
<AreaChart data={data} xKey="week" label="Pages written each week" seed="chart-area" />
</ChartContainer>
);
}Pie and ring
A ring with the total written in its middle.
- Sketches
- Letters
- Lists
- Recipes
| Sketches | 275 |
|---|---|
| Letters | 200 |
| Lists | 187 |
| Recipes | 123 |
import { ChartContainer, PieChart, type ChartConfig } from "@/components/ui/chart";
const data = [
{ name: "Sketches", value: 275 },
{ name: "Letters", value: 200 },
{ name: "Lists", value: 187 },
{ name: "Recipes", value: 123 },
];
const config = {
Sketches: { label: "Sketches" },
Letters: { label: "Letters" },
Lists: { label: "Lists" },
Recipes: { label: "Recipes" },
} satisfies ChartConfig;
export default function ChartPie() {
const total = data.reduce((sum, row) => sum + row.value, 0);
return (
<ChartContainer config={config} className="h-80 w-full max-w-sm">
<PieChart data={data} label="Pages by kind" seed="chart-pie">
<div className="text-4xl font-bold tabular-nums">{total}</div>
<div className="text-sm text-ink-3">pages</div>
</PieChart>
</ChartContainer>
);
}API reference
- ChartContainer config
Record<string, { label?, fill?, tone? }>Names the series. `fill` is shade, hatch, cross, dots or plain; `tone` is the pressure: ink, ink-2 or ink-3. By default each series takes the next style in turn.
- data
Record<string, string | number>[]One row for each point along the bottom.
- xKey
stringThe key in each row that names it.
- series
string[]Which keys to plot. By default every key in the config.
- BarChart stackeddefault
false booleanPile a row's series up instead of setting them side by side.
- LineChart curve / dotsdefault
"natural" / true "natural" | "linear" / booleanSmoothed or straight lines (areas default to straight), and a ring at each point.
- PieChart nameKey / valueKey / innerRadiusdefault
"name" / "value" / 0.55 string / string / numberWhich keys name and size each slice; 0 is a whole pie, up to 0.9 a thin ring. Children are set in the middle.
- format
(value: number) => stringHow values are written on the axis and in the tooltip.
- tooltip / legenddefault
true booleanPoint at a chart to read it; a key to the series under it.
- label
stringA name for the chart. It also adds a table of the data, hidden, for screen readers.
- seed
string | numberPins the drawing.
Pen settings
The drawing also takes draw, roughness, weight and speed, as props or from the nearest InkProvider. What each one does.