Ridgeline
Compare sampled distributions using a shared KDE domain, with median and quartile marks and an exact-statistics disclosure.
pnpm dlx shadcn@latest add @haze/ridgeline---
import { ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Distribution{label:string;samples:number[]}
interface Props{label?:string;distributions?:Distribution[];unit?:string;class?:string}
const{label="Response time distributions",unit="ms",distributions=[{label:"North",samples:[28,32,34,38,41,43,46,49,54,58,61,70]},{label:"West",samples:[35,42,46,48,49,52,53,55,58,60,66,81]},{label:"South",samples:[18,21,23,26,28,29,34,45,48,54,56,60]}],class:className}=Astro.props;
const rows=distributions.map(group=>({...group,samples:group.samples.filter(Number.isFinite).sort((a,b)=>a-b)})).filter(group=>group.samples.length);
const all=rows.flatMap(row=>row.samples),lo=all.length?Math.min(...all):0,hi=all.length?Math.max(...all):1,scale=Math.max(Math.abs(lo),Math.abs(hi),1);
const low=lo/scale,high=hi/scale,spread=high-low||.2,domainLow=low-spread*.15,domainHigh=high+spread*.15;
const x=(n:number)=>(n/scale-domainLow)/(domainHigh-domainLow)*300;
const quantile=(samples:number[],p:number)=>{const index=(samples.length-1)*p,a=Math.floor(index),t=index-a;return samples[a]*(1-t)+samples[Math.min(a+1,samples.length-1)]*t;};
const stats=rows.map((row,index)=>{const normalized=row.samples.map(v=>v/scale),mean=normalized.reduce((s,v)=>s+v/normalized.length,0),sd=Math.sqrt(normalized.reduce((s,v)=>s+(v-mean)**2/normalized.length,0)),bandwidth=Math.max(spread/60,1.06*sd*Math.pow(normalized.length,-.2)),density=Array.from({length:65},(_,i)=>{const value=domainLow+(domainHigh-domainLow)*i/64;return normalized.reduce((s,v)=>s+Math.exp(-.5*((value-v)/bandwidth)**2)/normalized.length/bandwidth,0);});return{label:row.label,index,count:row.samples.length,min:row.samples[0],q1:quantile(row.samples,.25),median:quantile(row.samples,.5),q3:quantile(row.samples,.75),max:row.samples.at(-1)!,density};});
const peak=Math.max(1,...stats.flatMap(row=>row.density)),height=Math.max(100,stats.length*50+35);
const shapes=stats.map((row,index)=>"M0 "+(index*50+65)+" "+row.density.map((d,i)=>"L"+(i/64*300)+" "+(index*50+65-d/peak*48)).join(" ")+"L300 "+(index*50+65)+"Z");
const axisLow=(low-domainLow)/(domainHigh-domainLow)*100,axisHigh=(high-domainLow)/(domainHigh-domainLow)*100;
const colors=["fill-brand/20 stroke-brand","fill-success/20 stroke-success","fill-warning/20 stroke-warning","fill-muted-foreground/20 stroke-muted-foreground"];
---
<figure data-haze-ridgeline data-stats={JSON.stringify(stats.map(({density,...row})=>row))} data-unit={unit} class={cn("grid min-w-0 gap-3 rounded-xl border border-border bg-card p-4.5 text-card-foreground",className)}>
<figcaption class="text-[0.9375rem]/5 font-medium tracking-[-0.01em] wrap-anywhere">{label}</figcaption>
{stats.length?<div class="relative w-full" style={"height:"+Math.max(8.75,height/16*0.85)+"rem"}><svg aria-hidden="true" viewBox={"0 0 300 "+height} preserveAspectRatio="none" class="absolute inset-0 size-full overflow-visible">{stats.map((row,index)=><g data-ridge={index} class="transition-[translate,opacity] duration-200 ease-snappy data-[dimmed]:opacity-40 data-[active]:-translate-y-1"><path d={shapes[index]} stroke-width="1.5" vector-effect="non-scaling-stroke" class={colors[index%colors.length]}/><path d={"M"+x(row.q1)+" "+(index*50+64)+"H"+x(row.q3)} stroke-width="4" vector-effect="non-scaling-stroke" class="stroke-foreground"/><path d={"M"+x(row.median)+" "+(index*50+48)+"V"+(index*50+69)} vector-effect="non-scaling-stroke" class="stroke-foreground"/></g>)}</svg>{stats.map((row,index)=><span data-ridge={index} aria-hidden="true" style={`top:${(index*50+55)/height*100}%`} class="absolute right-0 -translate-y-full rounded-xs bg-card/80 px-1 text-xs/4 text-muted-foreground transition-opacity duration-200 ease-snappy data-[dimmed]:opacity-75">{row.label}</span>)}</div>:<p class="text-[0.8125rem]/5 text-muted-foreground">No finite distribution samples.</p>}
<div class="relative h-5 text-xs/5 text-muted-foreground tabular-nums"><span style={`left:${axisLow}%`} class="absolute -translate-x-1/2 whitespace-nowrap">{lo.toLocaleString("en")} {unit}</span><span style={`left:${axisHigh}%`} class="absolute -translate-x-1/2 whitespace-nowrap">{hi.toLocaleString("en")} {unit}</span></div>
{stats.length>0&&<label data-ridge-control hidden class="grid gap-1 text-xs/5 text-muted-foreground">Inspect distribution<select data-ridge-select class="h-10 min-w-0 rounded-lg border border-frame bg-field px-3 text-[0.8125rem] text-foreground hover:border-frame-strong hover:bg-accent focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden">{stats.map((row,index)=><option value={index}>{row.label}</option>)}</select></label>}
<p data-ridge-readout role="status" aria-live="polite" class="min-h-10 text-xs/5 text-muted-foreground">Curves share one domain and density scale. The line marks the middle half; the tick marks the median.</p>
<details class="group min-w-0 border-t border-border pt-3"><summary class="flex min-h-7 cursor-pointer list-none items-center justify-between gap-2 rounded-sm text-[0.8125rem]/5 font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">Distribution statistics<ChevronDown aria-hidden="true" class="size-3.5 shrink-0 transition-[rotate] duration-200 ease-snappy group-open:rotate-180" /></summary><table class="mt-3 w-full table-fixed text-left text-xs/5"><caption class="sr-only">{label}</caption><thead><tr><th scope="col" class="p-1">Group</th><th scope="col" class="p-1">Min / Q1 / median / Q3 / max; n</th></tr></thead><tbody>{stats.map(row=><tr class="border-t border-border"><th scope="row" class="p-1 font-normal wrap-anywhere">{row.label}</th><td class="p-1 tabular-nums wrap-anywhere">{[row.min,row.q1,row.median,row.q3,row.max].map(v=>v.toLocaleString("en",{maximumFractionDigits:2})).join(" / ")} {unit}; n={row.count}</td></tr>)}</tbody></table></details>
</figure>
<script>
function initRidge(){document.querySelectorAll<HTMLElement>("[data-haze-ridgeline]:not([data-enhanced])").forEach(root=>{root.dataset.enhanced="";const rows:{label:string;count:number;min:number;q1:number;median:number;q3:number;max:number}[]=JSON.parse(root.dataset.stats||"[]"),select=root.querySelector<HTMLSelectElement>("[data-ridge-select]"),ridges=root.querySelectorAll<SVGElement|HTMLElement>("[data-ridge]");const show=(index:number)=>{const row=rows[index];if(!row)return;ridges.forEach(ridge=>{const i=Number(ridge.dataset.ridge);ridge.toggleAttribute("data-active",i===index);ridge.toggleAttribute("data-dimmed",i!==index);});root.querySelector("[data-ridge-readout]")!.textContent=row.label+": median "+row.median.toLocaleString("en",{maximumFractionDigits:2})+" "+(root.dataset.unit||"")+", middle half "+row.q1.toLocaleString("en",{maximumFractionDigits:2})+"–"+row.q3.toLocaleString("en",{maximumFractionDigits:2})+", range "+row.min+"–"+row.max+", "+row.count+" samples.";};root.querySelector("[data-ridge-control]")?.removeAttribute("hidden");select?.addEventListener("change",()=>show(Number(select.value)));show(select?Number(select.value):0);ridges.forEach(ridge=>ridge.addEventListener("pointerenter",()=>{const i=Number(ridge.dataset.ridge);if(select)select.value=String(i);show(i);}));});}
initRidge();if(!document.documentElement.hasAttribute("data-haze-ridgeline-listener")){document.documentElement.setAttribute("data-haze-ridgeline-listener","");document.addEventListener("astro:page-load",initRidge);}
</script>When to use
- Groups differ in the shape of a numerical distribution.
- Median and spread need to be compared without collapsing each group to one number.
When not to use
- Only one measurement per period is available. Use line-chart.
Installation
Add the Haze registry to components.json once, then install Ridgeline with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ridgelinenpx shadcn@latest add @haze/ridgelineyarn dlx shadcn@latest add @haze/ridgelinebunx --bun shadcn@latest add @haze/ridgelineFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| label | string | Response time distributions | Distribution comparison caption. |
| distributions | { label: string; samples: number[] }[] | – | Raw observations; nonfinite samples are removed and empty groups omitted. Curves use Gaussian KDE. |
| unit | string | ms | Suffix for the domain and statistics. |
| class | string | – | Additional classes on the chart figure. |
Keyboard interactions
- Arrow keys
- Choose a distribution using the native select.
Accessibility
- The group selector announces sample count, median, quartiles and range while its ridge lifts and others dim.
- Each ridge has a text label; the middle-half line and median tick are backed by a table of calculated statistics.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Ridgeline" with `npx shadcn@latest add @haze/ridgeline`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import Ridgeline from "@/components/haze/ui/ridgeline.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/ridgeline.md
Customize with real content
Adapt the Haze ridgeline ui for our product. Replace the demo values of these props with our real content: label, distributions, unit, class. Keep the layout, the heading level rules and these accessibility details: The group selector announces sample count, median, quartiles and range while its ridge lifts and others dim. Each ridge has a text label; the middle-half line and median tick are backed by a table of calculated statistics. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using ridgeline, check it fits: use it when groups differ in the shape of a numerical distribution.; median and spread need to be compared without collapsing each group to one number.. Avoid it when only one measurement per period is available. use line-chart.. Alternatives: @haze/line-chart, @haze/streamgraph, @haze/activity-heatmap.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.