Examples

A responsive SVG bar chart for comparing categorical values. Supports vertical and horizontal orientations, single or multi-series data (grouped/stacked), value labels, custom fills, hover tooltips, and click events. New capabilities include declarative and imperative bar highlighting, first-point normalisation, top-N clipping with overflow aggregation, and a graphics-free legend/label-only mode.

Basic

With Values

Custom Colors

Horizontal

Highlight — Declarative (highlightedIndex)

Clicking a button below sets highlightedIndex directly. The highlighted bar stays at full opacity while others dim. Set to null to clear.

Highlight — Imperative (onChartReady)

The chart fires onChartReady on mount with a ChartHighlightAPI handle. Call api.highlight(index) externally (e.g. from a voice narrator or a sibling component).

Normalise to First Point (normaliseToFirstPoint)

Each series' values are expressed as a percentage of its first data point (baseline = 100). This makes relative growth comparable across series with very different starting magnitudes.

Revenue
Users

Top-N Clipping (topN + overflowLabel)

Only the top 4 categories by value are shown individually. The remaining 6 are summed into a single bar labelled "Other".

Hide Bar Graphics (hideBarGraphics)

Bar rectangles are not rendered. Axis labels, gridlines, and any legend remain visible. Useful for legend-only or label-only companion views.

Per-bar value label override (valueLabel)

A data point's non-empty valueLabel renders verbatim as its value label, overriding the default valueFormat(value) output for that bar only. Other bars — including any whose valueLabel is an empty string — keep going through the normal formatter.

Labels near the axis max (outside → inside flip)

Crowded categories (rotate → thin)

Interactive legend (3 series × 4 categories)

Legend aggregates (aggregate + aggregateFormat)

$6,500
3.0%

Non-finite value in a stack — degrades to a zero contribution

A non-finite (NaN) value in one stacked series contributes zero height, and — critically — does not poison the running stack base for series stacked above it. "Organic" has no reading at Q2 below; its segment there collapses to zero while "Referral" still stacks correctly on top of "Direct", instead of the whole Q2 column turning to NaN geometry. See docs/CHART_INPUT_POLICY.md for the full input-shape table.

Direct
Organic
Referral

Documentation

A responsive SVG bar chart for comparing categorical values. Supports vertical and horizontal orientations, single or multi-series data (grouped/stacked), value labels, custom colors per data point, hover tooltips, click events, declarative and imperative bar highlighting, first-point normalisation across series, top-N clipping with overflow aggregation, and a graphics-free legend/label-only rendering mode. Zero external dependencies — built from pure SVG with CSS custom property theming.

Usage

<script>
  import { BarChart } from '@juspay/svelte-ui-components';

  const data = [
    { label: 'Jan', value: 4200 },
    { label: 'Feb', value: 3800 },
    { label: 'Mar', value: 5100 },
    { label: 'Apr', value: 4600 }
  ];
</script>

<BarChart {data} />

Horizontal Orientation

<BarChart {data} orientation="horizontal" />

Value Labels

<BarChart {data} showValues />

Multi-Series (Grouped)

<script>
  const series = [
    {
      name: 'Product A',
      data: [
        { label: 'Q1', value: 30 },
        { label: 'Q2', value: 50 }
      ]
    },
    {
      name: 'Product B',
      data: [
        { label: 'Q1', value: 20 },
        { label: 'Q2', value: 40 }
      ]
    }
  ];
</script>

<BarChart {series} groupMode="grouped" showLegend />

Multi-Series (Stacked)

<BarChart {series} groupMode="stacked" showLegend />

Custom Tooltip

<BarChart {data}>
  {#snippet tooltipSnippet(point, index)}
    <div style="background: #333; color: white; padding: 8px; border-radius: 4px;">
      <strong>{point.label}</strong>: ${point.value.toLocaleString()}
    </div>
  {/snippet}
</BarChart>

Empty State

<BarChart data={[]}>
  {#snippet empty()}
    <p>No data available.</p>
  {/snippet}
</BarChart>

Declarative Highlight

Set highlightedIndex to a zero-based category index to emphasise that bar and dim the others. Set to null to clear.

<script>
  let highlighted = $state(2);
</script>

<BarChart {data} highlightedIndex={highlighted} />
<button onclick={() => (highlighted = null)}>Clear highlight</button>

Imperative Highlight via onchartready

Receive a ChartHighlightAPI handle on mount to drive highlighting from outside the chart (e.g. synchronised with a voice narrator or a sibling component). The handle's type is always 'bar-chart'.

<script>
  import type { ChartHighlightAPI } from '@juspay/svelte-ui-components';

  let chartApi: ChartHighlightAPI | null = null;

  const handleReady = (api: ChartHighlightAPI) => {
    chartApi = api;
  };

  const highlightSecond = () => chartApi?.highlight(1);
  const clear = () => chartApi?.highlight(null);
</script>

<BarChart {data} onchartready={handleReady} />
<button onclick={highlightSecond}>Highlight Feb</button>
<button onclick={clear}>Clear</button>

Normalise to First Point

Each series' values are expressed as a percentage of its own first data point (baseline = 100). Useful when comparing relative growth across series with very different starting magnitudes.

<BarChart {series} normaliseToFirstPoint groupMode="grouped" showLegend showValues />

Top-N Clipping

Show only the top topN bars individually and aggregate the remainder into a single overflow bar.

<BarChart {data} topN={5} overflowLabel="Everything else" showValues />

Hide Bar Graphics

Render axes, gridlines, and legend without drawing any bar rectangles — useful for label-only or legend-only companion views.

<BarChart {data} hideBarGraphics showXAxis showYAxis />

Accessible name and description

Every chart drawing needs a name of its own. ariaLabel names the chart (it lands on the <svg>), and the optional ariaDescription adds the takeaway — trend, range, outliers — which is announced after the name:

<BarChart
  {series}
  ariaLabel="Revenue by month, January to June"
  ariaDescription="Revenue rises from 30 in January to 90 in December, dipping in March."
/>

Omit ariaLabel and a name is derived from the chart itself — "{yAxisLabel} bar chart" (the wording the old wrapping region used), else the series names, else "Bar chart" — so an unlabelled chart is still identifiable, but a name written for the page is almost always better. A blank string counts as omitted.

How the drawing is exposed depends on whether it holds controls:

  • A chart that draws bars is interactive: those marks are focusable role="button" elements, so the <svg> is exposed as a named role="group" rather than role="img". An image's children are presentational (ARIA), so marks left under one are dropped or announced inconsistently between browsers, and axe reports nested-interactive.
  • A chart with nothing to operate (every series hidden through the legend, or hideBarGraphics) is a static, named role="img".
  • The <svg> itself carries the name. A name on some wrapper elsewhere does not name the image inside it.
  • BarChart no longer wraps every chart in a role="region". That wrapper put one identically named landmark per chart on a page (axe: landmark-unique) and named the wrapper while the image inside stayed unnamed. A region exists only when scrollable is set — the wrapper is then a focusable scroll container, named "{chart name}, scrollable" so tabbing from the scroller into the chart does not announce the same words twice.
  • Tick labels and the value labels drawn on the chart are aria-hidden: each mark's own accessible name already says its category and value, so exposing them too would announce everything twice. The axis titles (xAxisLabel, yAxisLabel) stay exposed — they are where a unit or dimension is stated.
  • The description is an SVG <desc> with an instance-scoped id referenced by aria-describedby; every gradient and pattern id is instance-scoped too, so two charts on one page (or in two shadow roots) never resolve each other's references.

Keyboard access

Every bar is a focusable role="button" element that mirrors pointer hover on focus and fires its click event on Enter/Space. This is the same family-wide keyboard/tooltip contract PieChart and SankeyChart also implement — see PieChart's "Keyboard access" and "Synchronized legend recipe" sections for the full contract, including the pointer/focus/programmatic highlight precedence and the id-to-index re-resolution recipe for external legends.

Legend Aggregates

The aggregate sits beside the legend control, never inside it. When the legend is interactive (interactiveLegend), each entry is a toggle button, and every bit of text inside a button becomes part of its accessible name. Rendering the figure inside the toggle would make that name change whenever the data does — Revenue $6,500 one load, something else the next. A name that moves breaks voice-control targeting, breaks any consumer test matching it exactly (Testing Library's getByRole matches the whole string by default), and announces a figure as the control's identity rather than as information about the series.

So the button is named by its series alone, the aggregate is its sibling, and clicking the figure does not toggle the series.

Set aggregate on a series to show a computed value beside its legend label — e.g. a running total or an average. Omitted (or 'none'), the default, shows nothing and the legend renders exactly as before. Every kind, sum included, skips null/non-finite points rather than treating them as zero (this only changes the result for 'average', which shrinks its denominator, and 'min'/'max', which an absent point can never set); an aggregate over zero real points (an empty series, or one with only null/non-finite values) renders nothing rather than NaN or a fabricated 0, sum included. aggregateFormat defaults to the chart's own valueFormat, so pass it only when the aggregate needs a different unit (e.g. a percentage average on a currency-formatted chart).

<BarChart
  series={[
    { name: 'Revenue', data: [...], aggregate: 'sum', aggregateFormat: (v) => `$${v.toLocaleString()}` },
    { name: 'Conversion Rate', data: [...], aggregate: 'average', aggregateFormat: (v) => `${v.toFixed(1)}%` }
  ]}
  showLegend
/>

Invalid values

A stage value that is not a real number (NaN, Infinity, -Infinity) is handled rather than rendered. Which way depends on groupMode, because the two modes mean different things by "this value":

  • grouped / single — the value is excluded from the auto-computed domain. Its own bar is absent; every other bar keeps its correct height, and the value axis keeps its ticks.
  • stacked — the value contributes 0 to its category's total. The segment is still present at zero height, so the other series stacked in that same category keep their correct baselines.

The distinction matters because a stacked segment's value sets the baseline for everything above it, so excluding it would silently move other series.

Before this was enforced, one NaN anywhere in data made every bar's SVG path invalid — browsers drop such a path without an error, so the plot area emptied while the legend, category axis and focusable bar elements all stayed put, and the value axis rendered zero ticks. Accessible names are built from the raw values, so a screen reader still announced correct numbers for bars that were not being drawn at all. See Chart Input Policy.

Props

Prop Type Required Default Description
data BarChartDataPoint[] No - Array of {label, value, range?, color?, valueLabel?} for a single series. Provide either data or series. Each data point maps to one bar. range enables floating/range bars ([low, high]). color accepts a plain color string, a pattern fill, or a gradient fill (BarFill). A non-empty valueLabel renders verbatim as that bar's value label, overriding the default valueFormat(value) output; an empty string ('') is treated the same as an absent field and falls back to valueFormat(value).
series BarChartSeries[] No - Array of {name, data, color?, aggregate?, aggregateFormat?} for multi-series charts. When provided, overrides data. color accepts a plain color string, a pattern fill, or a gradient fill (BarFill). aggregate ('sum' | 'average' | 'min' | 'max' | 'none', default 'none') shows a computed value beside that series' legend label; aggregateFormat defaults to the chart's valueFormat. See "Legend Aggregates" below.
groupMode 'grouped' | 'stacked' No 'grouped' Layout mode for multi-series. grouped places bars side-by-side; stacked stacks them.
orientation 'vertical' | 'horizontal' No 'vertical' Bar orientation.
showValues boolean No false Whether to render the numeric value as a text label at the end of each bar. Disabled in stacked mode.
showGridlines boolean No true Whether to show dashed gridlines across the value axis.
showXAxis boolean No true Whether to render the X axis (ticks, labels, axis line).
showYAxis boolean No true Whether to render the Y axis.
showLegend boolean No false Whether to render the legend above the chart. Only applies when series is provided.
barPadding number No 0.2 Space between bars as a fraction of bar width (0 = no gaps, 0.5 = half-width gaps).
barRadius number No 4 Corner radius of each bar in pixels.
aspectRatio number No 16/9 Width-to-height ratio for the chart.
xAxisLabel string No - Text label shown below the X axis.
yAxisLabel string No - Text label shown beside the Y axis (rotated 90°).
yDomain [number, number] No auto Fixed [min, max] for the value axis.
valueFormat (value: number) => string No abbreviated Formatter for bar values. Default abbreviates with K/M/B suffixes.
stackNormalize boolean No false Normalises stacked values to 100%. Applies only when groupMode="stacked". Appends % to value labels unless valueFormat is supplied.
scrollable boolean No false Wraps the chart in a horizontally-scrollable container. Use with minBandWidth to keep bars readable.
minBandWidth number No 48 Minimum pixel width per category band when scrollable is true.
marginX number No auto Fixed horizontal inset (px) between the svg edges and the plot, overriding the auto layout's left/right margins. Use for edge-to-edge funnels where tick-label padding leaves dead space beside the first/last bars; short category labels recommended (long edge labels may clip).
onchartready (api: ChartHighlightAPI) => void No - Called once on mount with an imperative highlight handle. Use api.highlight(index) to emphasise a bar; api.highlight(null) clears. api.getCategories() returns the ordered label list. api.type is always 'bar-chart'.
highlightedIndex number | null No null Declarative highlight: the bar at this zero-based index is shown at full opacity; all others are dimmed. Overrides any index set via onchartready. Set to null to show all bars normally.
normaliseToFirstPoint boolean No false When true, each series' values are expressed as a percentage of that series' own first data point (baseline = 100). Series whose first point is zero are left unchanged.
topN number No - Keep only the top topN bars by value (descending). The remaining bars are summed into one overflow bar labelled by overflowLabel. Has no effect when the chart already has topN or fewer bars.
overflowLabel string No "Other" Label for the aggregated overflow bar produced by topN. Has no effect when topN is not set.
hideBarGraphics boolean No false When true, bar rectangles are not drawn. Axis labels, gridlines, and the legend remain visible.
tooltipSnippet Snippet<[BarChartDataPoint, number]> No - Custom tooltip content. Receives the hovered data point and its index. Replaces the default tooltip.
empty Snippet No - Content rendered when data is empty.
renderOverlay Snippet<[BarChartRenderContext]> No - Escape-hatch snippet rendered inside the SVG transform group after all bars. Receives { innerWidth, innerHeight, margin }.
ariaLabel string No derived Accessible name of the chart (aria-label on its <svg>). Say what the chart shows. When omitted a name is derived from yAxisLabel / the series names, else "Bar chart". See Accessible name and description.
ariaDescription string No - Optional longer description announced after the name (an SVG <desc> referenced by aria-describedby).
testId string No - Value for the data-pw attribute on the chart container.
classes string No - CSS class string applied to the top-level element.
interactiveLegend boolean No false Legend items become click/keyboard toggles for series visibility; hidden series are removed from the plot and the scales rescale to the remaining data.
hideLegendBelow number No 360 Hide the legend when the measured chart width is below this pixel value; 0 disables the behavior.
tooltipPortal boolean No false Render the tooltip into document.body (position: fixed) so scroll/overflow ancestors never clip it.

Bar corner rounding

Grouped and single bars round only their value end (per the design-system bar spec): a vertical bar rounds its top corners (bottom when the value is negative), a horizontal bar its right corners (left when negative), and floating [low, high] range bars round both ends. This keeps a backdrop or track bar behind the value bar from peeking through notches at the baseline corners (the old all-corner rx rounding). Stacked bars keep their existing outer-end-only rounding.

Events

Event Type Description
onbarclick (event: { index: number; dataPoint: BarChartDataPoint }) => void Fires when a bar is clicked. Receives the bar's index and data point.
onbarhover (event: { index: number; dataPoint: BarChartDataPoint } | null) => void Fires when the user hovers over or leaves a bar. null on leave.

CSS Variables

Override these custom properties to theme the component.

Variable Default CSS Property Description
--chart-background transparent background Background color of the chart container.
--chart-font-family inherit font-family Font family for all chart text.
--chart-transition-duration 0.2s transition Duration of hover transitions.
--chart-axis-color #666 stroke, fill Color of axis lines, tick marks, and tick labels.
--chart-axis-stroke-width 1 stroke-width Width of axis lines and tick marks.
--chart-axis-font-size 11px font-size Font size of tick labels.
--chart-axis-label-color #333 fill Color of axis labels (xAxisLabel, yAxisLabel).
--chart-axis-label-font-size 12px font-size Font size of axis labels.
--chart-gridline-color #e0e0e0 stroke Color of gridlines.
--chart-gridline-opacity 0.5 stroke-opacity Opacity of gridlines.
--chart-gridline-dash 4 4 stroke-dasharray Dash pattern for gridlines.
--chart-tooltip-background rgba(0,0,0,0.85) background Background of default tooltip.
--chart-tooltip-color #fff color Text color of default tooltip.
--chart-tooltip-font-size 12px font-size Font size of tooltip content.
--chart-tooltip-padding 8px 12px padding Inner padding of tooltip.
--chart-tooltip-border-radius 4px border-radius Border radius of tooltip.
--chart-tooltip-shadow 0 2px 8px rgba(0,0,0,0.2) box-shadow Shadow on the tooltip.
--chart-legend-gap 16px gap Space between legend items.
--chart-legend-font-size 12px font-size Font size of legend labels.
--chart-legend-swatch-size 12px width, height Size of color swatches in the legend.
--chart-legend-color #333 color Color of legend text.
--chart-empty-padding 32px 24px padding Padding around the empty state content.
--chart-empty-color #9ca3af color Text color of empty state default.
--barchart-bar-hover-opacity 1 opacity Opacity of the hovered bar.
--barchart-bar-highlighted-opacity 1 opacity Opacity of a bar emphasised via highlightedIndex or onchartready.
--barchart-bar-dimmed-opacity 0.3 opacity Opacity of non-highlighted / non-hovered bars when a highlight is active.
--barchart-value-color #333 fill Color of value labels.
--barchart-value-font-size 11px font-size Font size of value labels.
--barchart-value-font-weight 600 font-weight Font weight of value labels.
--barchart-scroll-area-height auto height Fixed height of the scroll area when scrollable is true.
--chart-transition-easing ease transition Easing curve of hover transitions. Falls back through --motion-easing. Shared across this library's chart family.

Dark mode

Chart colors resolve through CSS light-dark(). Set color-scheme on the chart's ancestor (or :root) so the correct side is chosen:

:root {
  color-scheme: light;
}
[data-theme='dark'] {
  color-scheme: dark;
}

Every --chart-* / component token can still be overridden per theme; overrides always win over the built-in light-dark() fallbacks.

Type Reference

import type { ChartHighlightAPI } from '@juspay/svelte-ui-components';

type ChartHighlightAPI = {
  highlight: (index: number | null) => void;
  getCategories: () => string[];
  type: 'bar-chart' | 'line-chart' | 'donut-chart';
};

type BarChartDataPoint = {
  label: string;
  value: number;
  range?: [number, number];
  color?: BarFill;
  valueLabel?: string;
};

type BarChartSeries = {
  name: string;
  data: BarChartDataPoint[];
  color?: BarFill;
};

Web Component

sui-bar-chart is registered by the web-component bundle. BarChart portals its tooltip (the tooltipPortal prop portals to document.body), which used to keep it off the element roster — a portalled node loses the shadow-scoped styles a custom element depends on. ChartTooltip now resolves its portal destination from the node's own root instead of hardcoding document.body, so the tooltip stays styled inside the shadow root and the element is safe to register.

<script type="module" src="@juspay/svelte-ui-components/wc"></script>

<sui-bar-chart show-values orientation="horizontal" bar-radius="6"></sui-bar-chart>

<script>
  const chart = document.querySelector('sui-bar-chart');
  chart.data = [
    { label: 'Jan', value: 4200 },
    { label: 'Feb', value: 3800 },
    { label: 'Mar', value: 5100 }
  ];
  chart.valueFormat = (value) => `₹${value.toLocaleString()}`;
  chart.onbarclick = ({ index, dataPoint }) => console.log(index, dataPoint.label);
</script>

Name and describe the chart with chart-aria-label / chart-aria-description (properties chartAriaLabel / chartAriaDescription). They are not aria-label / aria-description, which on a custom element name the host (a role-less element) rather than the drawing inside its shadow root; the host's own ARIA attributes are left alone. See Accessible name and description.

<sui-bar-chart chart-aria-label="Monthly revenue" chart-aria-description="Revenue peaks in June."></sui-bar-chart>

Web Component Events

onchartready, onbarclick, and onbarhover are available as JS properties, and each also dispatches a same-named DOM custom event (bubbles, composed) for a consumer who only calls addEventListener — chartready's detail is the chart API, barclick's and barhover's are { index, dataPoint }:

const chart = document.querySelector('sui-bar-chart');
chart.addEventListener('chartready', (e) => e.detail.highlight(2));
chart.addEventListener('barclick', (e) => select(e.detail.dataPoint.label));
chart.addEventListener('barhover', (e) => setHovered(e.detail?.dataPoint ?? null));

Scalar props are kebab-case attributes, coerced to their declared type: group-mode, orientation, show-values, show-gridlines, show-x-axis, show-y-axis, show-legend, bar-padding, bar-radius, aspect-ratio, max-height, min-height, x-axis-label, y-axis-label, stack-normalize, scrollable, min-band-width, margin-x, highlighted-index, normalise-to-first-point, top-n, overflow-label, hide-bar-graphics, interactive-legend, hide-legend-below, tooltip-portal, test-id. Booleans are presence-based, so show-values is on and removing the attribute turns it off. classes is a JS-property-only string (a whole class list rather than a single flag), so it has no attribute.

Everything else is a JS property, because arrays, objects, and functions cannot cross the HTML-attribute boundary:

const chart = document.querySelector('sui-bar-chart');
chart.data = data; // or chart.series = series for multi-series charts
chart.yDomain = [0, 100];
chart.valueFormat = (value) => `${value}%`;
chart.onchartready = (api) => api.highlight(2);
chart.onbarclick = ({ index, dataPoint }) => select(dataPoint.label);
chart.onbarhover = (event) => setHovered(event?.dataPoint ?? null);

empty is a slot, not a property — a plain-HTML consumer cannot construct a Svelte snippet:

<sui-bar-chart>
  <span slot="empty">No data for this period.</span>
</sui-bar-chart>

Leaving the slot empty keeps the component's own default, so an unslotted element still renders the chart's own fallback frame rather than a blank box.

Slots

Slot Replaces
empty The default empty state shown when data/series has no points.

Svelte-only: tooltipSnippet (Snippet<[BarChartDataPoint, number]>) and renderOverlay (Snippet<[BarChartRenderContext]>) both take arguments, so neither can be expressed as a named slot: a Web Component <slot> projects markup and does not forward Svelte snippet parameters, so the data point / index or render context would be silently dropped. Use the Svelte component directly when you need a custom tooltip or SVG overlay.