# Slope chart

> Connect before and after values on a shared scale, isolate each item, and read competition ranks and exact changes.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/slope-chart`
- File: `src/components/haze/ui/slope-chart.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/slope-chart

## Use when
- The direction of change between two periods is the main comparison.
- Readers need to see both value change and rank movement.

## Avoid when
- More than two ordered measurements form a trend. Use line-chart.

## Alternatives
- [line-chart](https://hazeui.com/ui/line-chart.md)
- [bar-chart](https://hazeui.com/ui/bar-chart.md)
- [radar-chart](https://hazeui.com/ui/radar-chart.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| label | `string` | Retention by cohort | no | Caption describing the paired measurement. |
| beforeLabel | `string` | Previous quarter | no | Name of the left period. |
| afterLabel | `string` | Current quarter | no | Name of the right period. |
| data | `{ label: string; before: number; after: number }[]` |  | no | Complete finite pairs, including negative and constant values. |
| unit | `string` | % | no | Measurement suffix. |
| class | `string` |  | no | Additional classes on the chart figure. |

## Accessibility
- Named cohort buttons reveal the before and after reading and both competition ranks in a polite status message.
- Incomplete pairs are omitted; the disclosure lists complete pairs in descending final-value order.
- Key Arrow Left / Arrow Right / Home / End: Move focus among named items; the order follows the reading direction.
- Key Enter / Space: Isolate or clear the focused slope.

## Agent prompts

### Install and use

Install the Haze UI component "Slope chart" with `npx shadcn@latest add @haze/slope-chart`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/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 SlopeChart from "@/components/haze/ui/slope-chart.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: https://hazeui.com/ui/slope-chart.md

### Customize with real content

Adapt the Haze slope-chart ui for our product. Replace the demo values of these props with our real content: label, beforeLabel, afterLabel, data, unit, class. Keep the layout, the heading level rules and these accessibility details: Named cohort buttons reveal the before and after reading and both competition ranks in a polite status message. Incomplete pairs are omitted; the disclosure lists complete pairs in descending final-value order. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using slope-chart, check it fits: use it when the direction of change between two periods is the main comparison.; readers need to see both value change and rank movement.. Avoid it when more than two ordered measurements form a trend. use line-chart.. Alternatives: @haze/line-chart, @haze/bar-chart, @haze/radar-chart.

## Example requests that should lead here
- Compare retention before and after a release, showing each cohort's exact change and starting and finishing rank.

## Source

```astro
---
import { ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Datum{label:string;before:number;after:number}
interface Props{label?:string;beforeLabel?:string;afterLabel?:string;data?:Datum[];unit?:string;class?:string}
const{label="Retention by cohort",beforeLabel="Previous quarter",afterLabel="Current quarter",unit="%",data=[{label:"Independent",before:62,after:78},{label:"Small teams",before:81,after:75},{label:"Studio",before:73,after:84},{label:"Enterprise",before:88,after:91}],class:className}=Astro.props;
const rows=data.filter(item=>Number.isFinite(item.before)&&Number.isFinite(item.after)),values=rows.flatMap(item=>[item.before,item.after]),lo=values.length?Math.min(...values):0,hi=values.length?Math.max(...values):1,magnitude=Math.max(Math.abs(lo),Math.abs(hi),1);
const y=(value:number)=>hi===lo?100:175-(value/magnitude-lo/magnitude)/(hi/magnitude-lo/magnitude)*150,rank=(value:number,key:"before"|"after")=>1+rows.filter(item=>item[key]>value).length;
const colors=["stroke-brand bg-brand","stroke-success bg-success","stroke-warning bg-warning","stroke-muted-foreground bg-muted-foreground","stroke-destructive bg-destructive"],text=(value:number)=>new Intl.NumberFormat("en",{maximumFractionDigits:2}).format(value)+unit;
const lineRows=rows.map((row,index)=>({...row,index,start:y(row.before),end:y(row.after),fromRank:rank(row.before,"before"),toRank:rank(row.after,"after")}));
---
<figure data-haze-slope-chart data-items={JSON.stringify(lineRows)} 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><div class="grid grid-cols-2 gap-2 text-xs/5 text-muted-foreground"><span class="wrap-anywhere">{beforeLabel}</span><span class="text-end wrap-anywhere">{afterLabel}</span></div>
 {rows.length?<div class="relative h-48 w-full"><svg aria-hidden="true" viewBox="0 0 300 200" preserveAspectRatio="none" class="absolute inset-0 size-full"><path d="M70 15V185M230 15V185" fill="none" vector-effect="non-scaling-stroke" class="stroke-border"/>{lineRows.map(row=><path data-slope-line={row.index} d={"M70 "+row.start+" L230 "+row.end} fill="none" stroke-width="2" vector-effect="non-scaling-stroke" class={cn("transition-opacity duration-200 ease-snappy data-[dimmed]:opacity-15",colors[row.index%colors.length])}/>)}</svg>{lineRows.map(row=><div data-slope-line={row.index} aria-hidden="true" class="transition-opacity duration-200 ease-snappy data-[dimmed]:opacity-15"><span style={`left:23.333%;top:${row.start/2}%`} class={cn("absolute size-2 -translate-1/2 rounded-full",colors[row.index%colors.length])}></span><span style={`left:76.667%;top:${row.end/2}%`} class={cn("absolute size-2 -translate-1/2 rounded-full",colors[row.index%colors.length])}></span><span style={`right:calc(76.667% + 0.625rem);top:${row.start/2}%`} class="absolute -translate-y-1/2 text-xs/4 text-muted-foreground tabular-nums">{text(row.before)}</span><span style={`left:calc(76.667% + 0.625rem);top:${row.end/2}%`} class="absolute -translate-y-1/2 text-xs/4 text-muted-foreground tabular-nums">{text(row.after)}</span></div>)}</div>:<p class="text-[0.8125rem]/5 text-muted-foreground">No complete before and after measurements.</p>}
 <div class="flex min-w-0 flex-wrap gap-1">{lineRows.map(row=><button type="button" data-slope-option={row.index} aria-pressed="false" disabled class="flex min-h-8 max-w-full items-center gap-2 rounded-lg px-2 text-xs/5 transition-colors duration-150 ease-snappy enabled:hover:bg-accent aria-pressed:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"><span aria-hidden="true" class={cn("size-2 shrink-0 rounded-full",colors[row.index%colors.length])}></span><span class="wrap-anywhere">{row.label}</span></button>)}</div>
 <p data-slope-readout role="status" aria-live="polite" class="min-h-10 text-xs/5 text-muted-foreground">Select a cohort to inspect both measurements and its rank movement.</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">Before, after and rank<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">Item</th><th scope="col" class="p-1">Measurements</th><th scope="col" class="p-1">Rank</th></tr></thead><tbody>{[...lineRows].sort((a,b)=>b.after-a.after).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">{text(row.before)} → {text(row.after)}</td><td class="p-1 tabular-nums">{row.fromRank} → {row.toRank}</td></tr>)}</tbody></table></details>
</figure>
<script>
function initSlope(){document.querySelectorAll<HTMLElement>("[data-haze-slope-chart]:not([data-enhanced])").forEach(root=>{
 root.dataset.enhanced="";const rows:{label:string;before:number;after:number;fromRank:number;toRank:number}[]=JSON.parse(root.dataset.items||"[]"),buttons=Array.from(root.querySelectorAll<HTMLButtonElement>("[data-slope-option]")),lines=root.querySelectorAll<SVGElement|HTMLElement>("[data-slope-line]");
 const select=(index:number)=>{buttons.forEach((button,i)=>button.setAttribute("aria-pressed",String(i===index)));lines.forEach(line=>line.toggleAttribute("data-dimmed",index>=0&&index!==Number(line.dataset.slopeLine)));const row=rows[index],unit=root.dataset.unit||"";root.querySelector("[data-slope-readout]")!.textContent=row?row.label+": "+row.before+unit+" to "+row.after+unit+", change "+(row.after-row.before>0?"+":"")+(row.after-row.before).toLocaleString("en",{maximumFractionDigits:2})+unit+". Rank "+row.fromRank+" to "+row.toRank+".":"All before and after slopes shown.";};
 buttons.forEach((button,i)=>{button.disabled=false;button.addEventListener("click",()=>select(button.getAttribute("aria-pressed")==="true"?-1:i));button.addEventListener("keydown",event=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(event.key))return;event.preventDefault();const rtl=getComputedStyle(root).direction==="rtl",forward=(event.key==="ArrowRight")!==rtl;buttons[event.key==="Home"?0:event.key==="End"?buttons.length-1:(i+(forward?1:-1)+buttons.length)%buttons.length].focus();});});
});}
initSlope();if(!document.documentElement.hasAttribute("data-haze-slope-chart-listener")){document.documentElement.setAttribute("data-haze-slope-chart-listener","");document.addEventListener("astro:page-load",initSlope);}
</script>
```
