012 / RECHARTS / AREA
Stack Flow Area
Additive multi-series stacked area chart with deterministic stack identity, truthful missing-value semantics, and contribution-over-time inspection.
- SPEC
- #012
- ENGINE
- Recharts
- FAMILY
- Area
- RENDERER
- svg
- STATUS
- preview
Installation
Checking public registry…
View local registry JSONCopied as source into your project (requires recharts).
Overview
Stack Flow Area is the multi-series composition chart of the Plotcn Area family. Engineered around strict additive semantics, stable series identity, and truthful missing-data policies, it visualizes how several independent parts combine into a meaningful whole across an ordered domain.
The primary analytical question answered by Stack Flow Area is:
"How does the total change over time, and how does each contributor participate in that total?"
Additive Identity Equation:
import { StackFlowArea } from "@/components/charts/recharts/area-stack-flow"const platformData = [ { month: "Jan", web: 120, ios: 80, android: 95 }, { month: "Feb", web: 130, ios: 94, android: 103 }, { month: "Mar", web: 138, ios: 112, android: 119 }, { month: "Apr", web: 149, ios: 123, android: 131 }, { month: "May", web: 162, ios: 135, android: 142 }, { month: "Jun", web: 175, ios: 148, android: 156 },]export function PlatformTrafficOverview() { return ( <StackFlowArea data={platformData} xKey="month" series={[ { key: "web", label: "Web Requests" }, { key: "ios", label: "iOS App" }, { key: "android", label: "Android App" }, ]} stackMode="absolute" showLegend interactiveLegend lockableTooltip valueFormatter={(v) => `${v.toLocaleString()} req/s`} showGrid /> )}Area-Family Positioning
Plotcn distinguishes clearly between single-magnitude and multi-series additive areas:
| Consideration | Prism Area (Component 011) | Stack Flow Area (Component 012) |
|---|---|---|
| Primary Question | "How much magnitude exists relative to baseline?" | "How do multiple parts assemble into a total over time?" |
| Input Structure | Single series (series={...}) | Multiple additive series (series={[...]}) |
| Visual Meaning | Area under one curve = accumulated volume | Vertical thickness = contribution; top edge = total sum |
| Baseline Rule | Configurable ("zero", "domain-min", custom) | Fixed at zero (additive composition requires zero baseline) |
| Ideal Metrics | Single service bandwidth, battery level, storage | Platform traffic, regional revenue, departmental headcounts |
| Unit Constraint | One unit | Strictly one shared unit across all stacked series |
Area-Family Principle: Use Stack Flow Area only when the configured series can truthfully and meaningfully be added together into a shared total.
Stack Model & Composition Geometry
Layer Thickness = Contribution; Top Silhouette = Total Sum
At every coordinate :
- Layer 1 (Bottom) anchors directly to the zero baseline .
- Layer 2 (Middle) rests upon the top boundary of Layer 1.
- Layer 3 (Top) rests upon the top boundary of Layer 2.
- Top Silhouette represents the arithmetic sum of all visible, valid series contributions.
- Layer Thickness represents that specific series' contribution at that observation.
Deterministic Stacking Order
Series order in the stack is strictly deterministic and matches the input series array. Series are never reordered dynamically by instantaneous value, total contribution, or alphabetical label. Dynamic reordering creates visual disjunctions ("layer flipping") that destroy temporal continuity.
Additive Data Contract
To preserve truthful visualization semantics, Stack Flow Area enforces three non-negotiable contract rules:
1. Values Must Be Additive
All series must represent mutually exclusive, additive quantities. Summing web requests, iOS requests, and Android requests yields total requests. Do not stack non-additive metrics such as percentages, temperatures, conversion rates, or latencies.
2. No Mixed Units
All series must share the identical physical, financial, or operational unit. Stacking USD with EUR or megabytes with milliseconds is mathematically invalid.
3. Non-Negative Additive Values
In V1, standard additive stacking requires non-negative values (). If negative values are detected in the dataset:
- Plotcn never silently clamps with
Math.max(0, val)(which falsifies data). - Plotcn never silently takes absolute values.
- The component halts rendering and displays a truthful
ChartErrorStateexplaining that negative values violate additive composition semantics.
Missing-Value Semantics: Missing is Not Zero
Known Zero Is Valid (0); Unavailable Data (null) Breaks the Stack
Zero is a valid, recorded measurement. The series contributes 0 height; remaining layers stack seamlessly, and the total is valid.
Under default 'gap' policy, missing data is not falsified into 0. The stack breaks cleanly, and tooltip reports 'Total: Incomplete'.
1. Gap Policy (missingValuePolicy="gap", Default)
When any visible series has a missing (null or undefined) contribution at coordinate :
- The stacked layer geometry breaks cleanly at that coordinate rather than silently tapering to zero.
- Tooltip displays
—for the missing series. - Incomplete Total Safeguard: The total is reported as
Incompleteinstead of displaying a deceptive partial sum that misleads viewers into thinking overall traffic plummeted.
2. Zero Policy (missingValuePolicy="zero")
If an application specifically and intentionally defines missing data as zero contribution (e.g. an API service with zero activity on weekends), setting missingValuePolicy="zero" explicitly substitutes $0$. This behavior is documented as an opt-in caller interpretation.
Stack Modes: Absolute vs. Percent
Stack Flow Area provides two purpose-built analytical modes:
| Mode | Layer Thickness | Top Silhouette | Scale Domain |
|---|---|---|---|
stackMode="absolute" (Default) | Raw contributor magnitude (e.g. ) | Total sum of visible series (e.g. ) | Dynamic: |
stackMode="percent" | Normalized proportional share (e.g. ) | Constant ceiling | Fixed: |
Percent Mode Precision & Zero-Total Protection
In percent mode:
- Proportions are derived dynamically from the visible series at each .
- Zero-Total Safety: If all visible series at an observation equal zero (), the denominator is zero. Rather than producing
NaNor crashing SVG paths, Plotcn safely normalizes each share to0%and renders a zero-height baseline stack. - Tooltip Reporting: In percent mode, tooltips display both the normalized percentage and the raw contributing value (e.g.
120 · 35.3%).
Deterministic Series Identity & Color Precedence
Series identity remains invariant under dynamic changes:
| Series Order | Default Semantic Token | Fallback Hex |
|---|---|---|
series[0] (Bottom) | var(--chart-1) | #3b82f6 (Theme Blue) |
series[1] (Middle) | var(--chart-2) | #10b981 (Emerald) |
series[2] (Top) | var(--chart-3) | #f59e0b (Amber) |
series[3] | var(--chart-4) | #8b5cf6 (Purple) |
series[4] | var(--chart-5) | #ec4899 (Pink) |
Stable Identity When Toggling Series
When a user hides a series via the interactive legend:
- Remaining visible layers restack to form a valid contiguous area.
- The Y-axis domain recomputes to the new visible total.
- Crucial Invariant: Hidden series do not cause color reassignments. If
iOS(--chart-2) is hidden,Androidremains--chart-3. It never shifts to--chart-2.
Color Precedence
Color assignment follows standard Plotcn multi-series rules:
- Explicit Series Override:
series.color(e.g.color: "#2563eb"). - Palette Token Fallback: Theme semantic CSS variable
var(--chart-N).
Interactive Legend Controls
For multi-series area composition, a legend is vital for layer identification. Stack Flow Area provides a fully interactive, keyboard-accessible legend:
- Click / Tap: Toggle visibility of any series.
- Keyboard (Tab + Enter / Space): Standard accessible focus and toggle flow with live
aria-pressedstates. - Area Fill Swatches: Swatches render as rectangular filled area blocks matching each layer's fill and border styling.
- All-Hidden Recovery: If all series are toggled off, the chart displays a clean recovery state with an action to restore all series.
Component Props
| Property | Type | Default | Required | Description |
|---|---|---|---|---|
data | readonly TData[] | [] | Required | Readonly array of observation records. Caller data is never mutated. |
xKey | keyof TData & string | — | Required | Property name for horizontal domain coordinates (e.g., month, date). |
series | readonly StackFlowSeries<TData>[] | — | Required | Array of series descriptors ({ key, label, color?, valueFormatter? }). |
stackMode | "absolute" | "percent" | "absolute" | Optional | Composition mode: raw additive totals or 100% normalized relative shares. |
missingValuePolicy | "gap" | "zero" | "gap" | Optional | Missing-value handling: honest break with incomplete total, or explicit zero-fill. |
height | number | string | 320 | Optional | Container height in pixels or standard CSS dimension strings. |
curve | "monotone" | "linear" | "step" | "monotone" | Optional | Curve interpolation algorithm shared identically across all stacked layers. |
fillOpacity | number | 0.45 | Optional | Controlled fill opacity between 0 and 1, ensuring layer distinction without mud. |
gradientMode | "none" | "vertical-fade" | "none" | Optional | Optional vertical opacity gradient per layer with collision-safe React.useId(). |
showGrid | boolean | true | Optional | Whether to render subtle horizontal Cartesian grid reference lines. |
showLegend | boolean | true | Optional | Whether to render the series identity legend. |
interactiveLegend | boolean | true | Optional | Enables clickable/keyboard buttons in the legend to toggle series visibility. |
lockableTooltip | boolean | true | Optional | Enables persistent tooltip locking via click, tap, or Enter/Space. |
selectionColor | string | "var(--chart-selection)" | Optional | Accent color for the locked crosshair and inspection status indicator. |
animation | "draw" | "fade" | "none" | "draw" | Optional | Restrained entrance reveal animation. Bypassed under prefers-reduced-motion. |
valueFormatter | (value: number) => string | n.toLocaleString() | Optional | Formatter for Y-axis scale ticks and default tooltip contributor values. |
xFormatter | (value: string | number) => string | String | Optional | Custom formatter for horizontal domain tick labels. |
title | string | "Stack Flow Area Chart" | Optional | Accessible title for assistive technologies and screen readers. |
description | string | undefined | Optional | Accessible description detailing series composition and keyboard shortcuts. |
Installation
Install Stack Flow Area directly into your project using the shadcn CLI:
Checking public registry…
View local registry JSONCopied as source into your project (requires recharts).
Keyboard Navigation Reference
Stack Flow Area provides a dual-surface keyboard accessibility model:
| Key | Control Target | Action |
|---|---|---|
| → / ArrowRight | Plot Surface | Inspect next observation across all visible stacked series |
| ← / ArrowLeft | Plot Surface | Inspect previous observation across all visible stacked series |
| Home | Plot Surface | Jump inspection directly to the first observation |
| End | Plot Surface | Jump inspection directly to the latest observation |
| Enter or Space | Plot Surface | Lock or unlock persistent inspection at the active coordinate |
| Escape | Plot Surface | Dismiss locked inspection and release pinned tooltip |
| Tab | Legend Items | Cycle focus through interactive series toggle buttons |
| Enter or Space | Legend Button | Toggle visibility of focused series (re-stacks layers and recalculates total) |
Props Reference & Interactive Prop Explorer
Inspect every component property, customize semantic color roles live with instant visual feedback, and copy production-ready code with active prop configurations.
Colors & Appearance Configuration
Customize primary, reference, or annotation series colors. Defaults derive from Plotcn theme tokens.
<StackFlowArea
data={data}
xKey="date"
seriesKey="value"
/>"absolute" plots raw additive quantities and stack totals; "percent" normalizes layers to proportional 100% shares.
stackMode="absolute"Default: "absolute"Curve interpolation algorithm shared across all stacked area boundaries.
curve="monotone"Default: "monotone"Opacity of stacked area layers (clamped between 0.1 and 1.0) ensuring layers remain distinguishable.
fillOpacity={0.65}Default: 0.65Gradient styling for layer fills. "vertical-fade" produces subtle top-to-bottom opacity fade per layer.
gradientMode="none"Default: "none"Whether to render subtle horizontal Cartesian grid reference lines.
showGrid={true}Default: trueWhether to render the series identity legend with area fill swatch samples.
showLegend={true}Default: trueWhether legend items can be clicked/keyboard-activated to toggle layer visibility. Restacks remaining layers without shifting colors.
interactiveLegend={true}Default: true"gap" truthfully breaks geometry and flags total incomplete; "zero" explicitly coerces nulls to 0 for continuous stacking.
missingValuePolicy="gap"Default: "gap"| Property | Type | Default | Required | Description |
|---|---|---|---|---|
dataReq | readonly TData[] | [] | Yes | Readonly array of observation records. Caller data is never mutated or sorted in place. |
xKeyReq | keyof TData & string | — | Yes | Property name on data records for horizontal domain coordinates. |
seriesReq | readonly StackFlowSeries<TData>[] | [] | Yes | Ordered array of additive series definitions. Geometry stacks from series[0] at bottom to series[n-1] at top. |
stackModeOpt | "absolute" | "percent" | "absolute" | No | "absolute" plots raw additive quantities and stack totals; "percent" normalizes layers to proportional 100% shares. |
heightOpt | number | string | 320 | No | Container height in pixels or standard CSS dimension strings. |
curveOpt | "monotone" | "linear" | "step" | "monotone" | No | Curve interpolation algorithm shared across all stacked area boundaries. |
domainOpt | [number, number] | ["auto", "auto"] | "auto" | "auto" | No | Explicit Cartesian Y scale domain. In percent mode, domain is fixed strictly to [0, 100]. |
fillOpacityOpt | number | 0.65 | No | Opacity of stacked area layers (clamped between 0.1 and 1.0) ensuring layers remain distinguishable. |
gradientModeOpt | "none" | "vertical-fade" | "none" | No | Gradient styling for layer fills. "vertical-fade" produces subtle top-to-bottom opacity fade per layer. |
string | "var(--chart-selection)" | No | Accent color for the locked crosshair and locked inspection status indicator. | |
showGridOpt | boolean | true | No | Whether to render subtle horizontal Cartesian grid reference lines. |
showLegendOpt | boolean | true | No | Whether to render the series identity legend with area fill swatch samples. |
boolean | true | No | Whether legend items can be clicked/keyboard-activated to toggle layer visibility. Restacks remaining layers without shifting colors. | |
boolean | true | No | Enables persistent tooltip pinning on click, tap, or Enter/Space. | |
"gap" | "zero" | "gap" | No | "gap" truthfully breaks geometry and flags total incomplete; "zero" explicitly coerces nulls to 0 for continuous stacking. | |
animationOpt | "draw" | "fade" | "none" | "draw" | No | Initial reveal animation style. Bypassed automatically when reduced motion is preferred. |
(value: number) => string | — | No | Custom formatter for Y-axis numbers and default tooltip metric values. | |
xFormatterOpt | (value: string | number) => string | — | No | Custom formatter for horizontal domain tick labels. |
Component Variants & Edge States
Production cookbooks showcasing configuration variants alongside verified handling of loading, empty data, and network error states.
Platform Traffic Composition
Standard multi-series stacked area visualization showing monthly requests by client platform (Web, iOS, Android) combining into a stack total.
100% Relative Share Mode
Normalized 100% stacked area illustrating how each platform's proportional contribution evolves over time independent of total volume.
Truthful Incomplete Stack
Under default gap policy, missing observations are never silently coerced to zero. Incomplete stacks break cleanly and tooltips report incomplete totals.
Constant Total with Changing Mix
Demonstrates stacked area composition when the overall volume remains stable while contributor shares shift across quarters.
Skeletons indicate runtime fetch or pending data queries.
Handles empty collections ([]) gracefully without crashing.
Graceful failure banner when data source or script fails.
Responsive Behavior
Stack Flow Area maintains full compositional integrity across all viewport widths without clipping or dropping layers:
- Desktop (): Full-width stacked visualization with horizontal legend swatches, complete Y-axis numeric scale, and multi-row shared tooltip with individual contributions and stack total.
- Tablet (): Wrapped legend layout, reduced horizontal tick density, and synchronized nearest-X inspection.
- Mobile ():
- All layers remain visible in the stack (layers are never silently pruned to save space).
- Legend controls wrap cleanly into 32px touch targets with no horizontal document overflow.
- Locked inspection tooltip displays compactly with high-contrast badge and dismiss shortcut.
- State Preservation: Switching viewport sizes, rotating devices, or toggling themes preserves all active series selections and locked inspection coordinates.
Container-Driven Breakpoints
Stack Flow Area preserves full multi-series composition and layer distinction across all viewport widths without dropping layers or overflowing.
Spacious stacked area flow, inline legend with area fill swatches, and multi-row inspection tooltip with contributor breakdown and stack total.
Adaptive wrapped legend, thinned categorical ticks, and synchronized nearest-X inspection.
Compact gutters, 32px touch targets for interactive legend toggles, and compact locked tooltip with no page-level overflow.
Accessibility & Keyboard Navigation
Stack Flow Area is designed from first principles for assistive technology compliance:
- Semantic Shell: Encapsulated within a
<figure role="region" tabIndex={0}>element with comprehensivearia-labelledbyandaria-describedbyassociations. - Fact-Based Screen Reader Summary: Announces the total number of series, visible series count, number of time observations, current stack mode (
absoluteorpercent), and domain bounds. - Structured Data Alternative: Includes an accessible, off-screen semantic HTML
<table>rendering all observations, individual series contributions, and computed stack totals for screen readers. - Decoupled Focus Flow: A single tab stop accesses the chart observation plot, while series toggle buttons in the legend are standard focusable
<button>elements in the natural DOM tab flow. - Missing vs. Zero Distinction: Screen reader announcements clearly distinguish between a known zero contribution and an unavailable observation.
- Reduced Motion: All layer entrance transitions and restacking animations immediately render their final geometry when
prefers-reduced-motion: reduceis detected.
Accessibility & Navigation Standards
Single keyboard tab stop on root figure with ArrowLeft, ArrowRight, Home, End, Enter, and Escape shortcuts. Separate standard button tab stops for interactive legend toggles.
Container mounts as region with explicit assistive label.
Layer boundaries, rectangular fill swatches, tooltip text readouts, and off-screen structured data table provide accessible non-color differentiation.
Embeds visually hidden summary (.sr-only) declaring: “Announces domain observation coordinate, count of visible vs configured series, stack mode, individual series contributions, and computed stack total.”
All entrance reveal animations and restacking transitions immediately bypass when prefers-reduced-motion is detected in user system preferences.
| Key | Action |
|---|---|
| ArrowRight | Inspect next chronological observation across visible series. |
| ArrowLeft | Inspect previous chronological observation across visible series. |
| Home | Jump inspection directly to the first observation. |
| End | Jump inspection directly to the final observation. |
| Enter / Space | Lock or unlock persistent inspection at the active coordinate. |
| Escape | Release locked selection and dismiss active inspection tooltip. |
| Tab | Move focus to interactive series visibility controls in the legend. |
Data Safety Guarantee
Stack Flow Area guarantees complete data integrity and contract enforcement:
- ✓ Additive Consistency: Enforces single-unit additive composition across all stacked series.
- ✓ Missing is Not Zero: Missing values (
null,undefined) produce an honest break; incomplete totals are explicitly flagged asIncomplete. - ✓ Zero Remains Valid: Real zero contributions ($0$) are accurately rendered at zero thickness without being dropped as falsy.
- ✓ Negative Rejection: Negative values are never clamped or altered; they trigger a truthful
ChartErrorState. - ✓ Divide-by-Zero Protection: In percent mode, observations where all series equal zero safely resolve to 0% without generating
NaNor invalid SVG coordinates. - ✓ Stable Series Identity: Canonical series order governs palette tokens; toggling series visibility never recolors remaining layers.
- ✓ Deterministic Stacking: Stack order is fixed to input series definition; layers never rearrange dynamically over time.
- ✓ Immutability: Caller data arrays and series descriptors are treated as readonly and are never mutated.
Internal Architecture & File Dependencies
Source-first ownership model. Inspect the exact component call tree, dependencies, and full implementation below.
Handles container dimension measurement and CSS token scoping
Coordinates coordinate scales, Cartesian grid, and Area polygon rendering with stackId
Interactive button controls with rectangular area swatches and keyboard accessibility