Chart

Alignment target:@astryxdesign/charts v0.1.9 · Chart

Overview #

@astryx-vue/charts uses d3 to calculate scales and geometry, then renders SVG with Vue. Each chart contains a <Chart> canvas and one or more series, such as lines, bars, or areas.

Install #

Shell
pnpm add @astryx-vue/charts

@astryx-vue/charts depends on @astryx-vue/core and vue. Make sure both are installed in your project.

The library includes base styles. Import the full stylesheet in your entry file:

TypeScript
import '@astryx-vue/charts/charts.css'

To load styles on demand, import individual files from @astryx-vue/charts/styles/, such as chart.css, chart-axis.css, chart-grid.css, chart-legend.css, chart-tooltip.css, or chart-swatch.css.

Your first chart #

A minimal chart requires three props on <Chart>:

  • data: An array of objects where each item represents one row of data.
  • xKey: The field name in each row to use for the horizontal x-axis.
  • series: An array of series definitions created with functions such as line() or bar().

Here is the shortest working line chart:

Vue
<script setup lang="ts">
import { Chart, ChartAxis, ChartGrid, line } from '@astryx-vue/charts'

// 1. Prepare data
const data = [
  { month: 'Jan', revenue: 100, cost: 60 },
  { month: 'Feb', revenue: 150, cost: 80 },
  { month: 'Mar', revenue: 120, cost: 70 },
]

// 2. Define series: two lines reading revenue and cost
const series = [
  line('revenue', { label: 'Revenue' }),
  line('cost', { label: 'Cost' }),
]
</script>

<template>
  <Chart :data="data" x-key="month" :series="series" :height="260" legend tooltip>
    <template #grid>
      <ChartGrid />
    </template>
    <template #axes>
      <ChartAxis position="bottom" />
      <ChartAxis position="left" />
    </template>
  </Chart>
</template>

Here is the live result:

Chart — Line chart

Line chart with revenue and cost series, grid lines, axes, a bottom legend, and hover tooltips.

Series #

A series defines a visual representation of data on the chart. A series object holds internal state during layout and rendering. Because of this, provide each series object to one <Chart> only. Create fresh series definitions for each chart instance.

When data has missing values (null, undefined) or non-finite numbers (NaN, Infinity), line marks break cleanly and leave an empty gap. They never drop to zero or draw false connections across gaps.

When yDomain is omitted, yBaseline controls how the y-axis range is calculated:

  • 'auto' (default): Marks with a zero baseline (bars, areas) include 0 in the scale. Continuous point marks (lines, dots) keep small padding on both ends so points do not clip at the edges.
  • 'zero'': Expands the scale symmetrically around 0. Useful for values that swing positive and negative, such as profit and loss.
  • 'data': Clamps tightly to the minimum and maximum data values without forcing 0 or adding edge padding.

Line (line) #

A line series shows continuous trends over time or across categories.

TypeScript
declare function line(dataKey: string, options?: LineOptions): SeriesDef
OptionTypeDefaultDescription
colorstringAuto from theme paletteLine color.
curve'linear' | 'monotone' | 'natural' | 'step''monotone'Curve interpolation method. Options are linear, monotone cubic spline, natural spline, and step.
strokeWidthnumber2Line stroke width in pixels.
dotsbooleanfalseWhether to render solid circular dots at each data point.
labelstringdataKeyHuman-readable name shown in legends and tooltips.

Bar (bar) #

A bar series compares magnitudes across categories or time steps. Bars with the same group split the category bandwidth and sit side by side. Bars with the same stack stack on top of each other.

TypeScript
declare function bar(dataKey: string, options?: BarOptions): SeriesDef
OptionTypeDefaultDescription
colorColorAccessorAuto from theme paletteBar fill color. Accepts a color string or a function (datum, index) => string.
opacitynumber1Bar opacity, between 0 and 1.
radiusnumber4Corner radius on the bar top in pixels. In stacked bars, only the top segment receives rounded corners.
stackstringundefinedStack group name. Series sharing a stack accumulate upward from the baseline.
groupstringundefinedSide-by-side group name. Series sharing a group sit next to each other within each category.
labelstringdataKeyHuman-readable name shown in legends and tooltips.

Chart — Bar chart

Bar chart example: revenue and cost share a group to display side by side for each month.

Area (area) #

An area series fills the region below a line. It is useful for showing total volume and changing proportions over time. Giving multiple area series the same stack name stacks them in order.

TypeScript
declare function area(dataKey: string, options?: AreaOptions): SeriesDef
OptionTypeDefaultDescription
colorstringAuto from theme paletteArea fill color.
opacitynumber0.3Area fill opacity.
curve'linear' | 'monotone' | 'natural' | 'step''monotone'Curve interpolation algorithm.
stackstringundefinedStack group name. Areas sharing a stack stack sequentially.
gradientbooleanfalseWhether to apply a vertical gradient fill.
strokebooleantrueWhether to draw a stroke line along the top edge of the area.
labelstringdataKeyHuman-readable name shown in legends and tooltips.

Chart — Stacked area chart

Stacked area chart: cost and profit share a stack identifier to show overall totals.

Dot (dot) #

A dot series shows the distribution of discrete data points.

TypeScript
declare function dot(dataKey: string, options?: DotOptions): SeriesDef
OptionTypeDefaultDescription
colorColorAccessorAuto from theme paletteDot color. Accepts a color string or a per-point accessor function.
radiusnumber4Dot radius in pixels.
opacitynumber0.8Dot opacity.
dodgebooleanfalseWhen multiple points share the same x value, offsets them horizontally to reduce overlap.
labelstringdataKeyHuman-readable name shown in legends and tooltips.

Chart — Dot chart

Dot chart example: distribution of test scores across sample sizes and control groups.

Band (band) #

A band series fills a translucent area between an upper and a lower boundary field. It is often used to show forecast confidence intervals. Band marks are annotations, so they do not appear in legends or tooltips.

TypeScript
declare function band(options: BandOptions): SeriesDef
OptionTypeDefaultDescription
upperstringRequiredField name for the upper boundary value.
lowerstringRequiredField name for the lower boundary value.
colorstring'var(--color-accent)'Fill color for the band area.
opacitynumber0.15Fill opacity for the band area.

Reference line (referenceLine) #

A reference line marks a specific horizontal or vertical threshold on the chart, or fills a shaded region between two horizontal values. Reference lines are annotations, so they do not appear in legends or tooltips.

TypeScript
declare function referenceLine(options: ReferenceLineOptions): SeriesDef
OptionTypeDefaultDescription
ynumberundefinedDraws a horizontal line at this y-axis value.
y2numberundefinedSecond y-axis value. Providing both y and y2 shades a reference band between them.
xnumberundefinedDraws a vertical line at this x-axis value.
colorstring'var(--astryx-color-border-emphasized)'Line or band fill color.
strokeWidthnumber1Stroke width in pixels.
strokeDasharraystringundefinedDash pattern string, such as '4 4'.
labelstringundefinedText label displayed alongside the line.
labelPosition'start' | 'end''end'Label placement along the line: start/end corresponds to left/right for horizontal lines, and bottom/top for vertical lines.
bandOpacitynumber0.1Fill opacity for the reference band (active only when y2 is set).

Chart — Band and reference line

Band and reference line: shaded forecast interval in the background, actual line in the middle, and a dashed target threshold on top.

Error bar (errorBar) #

An error bar (whisker) displays value uncertainty. It is usually paired with bar() or dot(). Boundary fields use absolute values, allowing asymmetric error intervals. If a row lacks an upper or lower bound, the chart skips that point instead of drawing misleading lines to zero. Error bars are annotations, so they do not appear in legends or tooltips.

TypeScript
declare function errorBar(options: ErrorBarOptions): SeriesDef
OptionTypeDefaultDescription
highstringRequiredField name for the upper bound (absolute value).
lowstringRequiredField name for the lower bound (absolute value).
colorstring'var(--astryx-color-text-primary)'Stroke color.
strokeWidthnumber1.5Stroke width in pixels.
capWidthnumber8Width in pixels of the horizontal end caps.

Chart — Error bars

Error bars: paired with a bar chart to display group averages alongside 95% confidence intervals.

Candlestick (candlestick) #

A candlestick series displays open, high, low, and close prices over time, commonly used in financial charts.

TypeScript
declare function candlestick(options: CandlestickOptions): SeriesDef
OptionTypeDefaultDescription
openstringRequiredField name for the open price.
highstringRequiredField name for the high price.
lowstringRequiredField name for the low price.
closestringRequiredField name for the close price.
upColorstring'var(--astryx-color-success)'Color for up candles, where close is greater than or equal to open.
downColorstring'var(--astryx-color-error)'Color for down candles, where close is lower than open.

Chart — Candlestick

Candlestick chart: displays daily price movements for a stock or commodity over a week.

Axes, grid, legend, tooltip #

Supporting chart elements are provided as individual components. You can combine and configure them independently. Setting legend or tooltip to true on <Chart> enables their defaults. Pass an object to customize position and layout.

Axes (ChartAxis) #

Axes render along chart edges to display ticks and label text.

PropTypeDefaultDescription
position'top' | 'right' | 'bottom' | 'left'RequiredEdge to place the axis on.
tickCountnumber5Desired number of ticks. d3 uses this as a hint to find clean intervals.
maxTicksnumberundefinedMaximum number of tick labels to render. Excess ticks are skipped at uniform intervals.
tickFormat(value: unknown) => stringundefinedCustom tick label formatting function.
truncatenumberundefinedMaximum characters for tick labels before truncating with an ellipsis.
animatedbooleantrueWhether to smoothly animate tick transitions when positions change.
showAxisLinebooleantrue on bottom axis onlyWhether to render the axis baseline. If showTicks is true, the baseline is always drawn regardless of position.
showTicksbooleanfalseWhether to draw short perpendicular tick lines at each step.

Grid (ChartGrid) #

Grid lines render behind series elements to help align values visually.

PropTypeDefaultDescription
horizontalbooleantrueWhether to draw horizontal grid lines.
verticalbooleanfalseWhether to draw vertical grid lines.
tickCountnumber5Approximate number of grid lines. Matching this with <ChartAxis> aligns grid lines with axis ticks.

Legend (ChartLegend) #

A legend lists series names alongside their representative colors. Setting legend on <Chart> shows the legend (off by default), or use the <ChartLegend> component directly.

PropTypeDefaultDescription
itemsLegendItem[][]Explicit array of legend items. Inferred automatically from series when omitted.
position'top' | 'bottom' | 'start' | 'end''bottom'Docking side relative to the chart canvas. start and end follow reading direction.
alignment'start' | 'center' | 'end''start'Alignment of items along the docked edge.

Tooltip (ChartTooltip) #

A tooltip displays details for the data row under the pointer.

PropTypeDefaultDescription
seriesreadonly SeriesDef[]Injected by ChartSeries definitions. When using <ChartTooltip> directly, pass the same series array.
hoverIndicatorbooleantrueWhether to draw hover indicators. Bars highlight the active column, while lines, areas, and dots draw a vertical rule.
showHoverDotsbooleantrueWhether to highlight active data points with dots (skipped automatically on bars).
placement'auto' | 'right' | 'left' | 'top''auto'Card placement relative to the active point. auto defaults to the right and flips left when room runs out.

Swatch (ChartSwatch) #

A swatch renders a small color marker representing a series, useful inside legends or custom tooltips.

PropTypeDefaultDescription
colorstringRequiredFill color value.
variant'square' | 'line''square'Swatch shape. square renders a small square (for bars); line renders a short horizontal line (for lines and areas).

Custom tooltip content #

When the default tooltip layout is not enough, customize the card content through the #tooltip slot on <Chart>. The slot exposes the active xValue and row details in rows:

Vue
<template>
  <Chart :data="monthly" x-key="month" :series="series" tooltip>
    <template #tooltip="{ xValue, rows }">
      <div class="my-custom-tooltip">
        <strong>{{ xValue }}</strong>
        <div v-for="row in asRows(rows)" :key="row.key">
          <ChartSwatch :color="row.color" variant="line" />
          {{ row.label }}: {{ money(row.value) }}
        </div>
      </div>
    </template>
  </Chart>
</template>

Chart — Custom tooltip

Custom tooltip: uses the #tooltip slot to read active data and render a custom layout.

Colors #

When a series does not set an explicit color, the chart assigns one automatically in order from the active theme palette.

All chart colors use CSS variables underneath. When switching themes or toggling dark mode, chart colors update automatically without re-rendering the SVG tree.

To inspect or use the current chart palette programmatically, call useChartColors(). It returns a shared object across the package:

  • categorical(n: number): Returns an array of n categorical colors. If n exceeds palette size, colors cycle.
  • sequential: Sequential color scale helper supporting nine hues (blue, shamrock, orange, pink, purple, red, teal, yellow, gray). Passing a count n returns a gradient color array.
  • diverging: Two-pole diverging palette helper. Provides positiveNegative, coldHot, and custom (custom hues on each pole).
  • semantic: Semantic status colors, containing positive, negative, warning, and neutral.
  • structural: Structural colors for chart framing, containing axis, grid, tick, and label.
  • alpha(color: string, opacity: number): Generates a color with an alpha channel for a given opacity. CSS variables use color-mix() automatically.

Formatting functions #

The library includes formatting helpers for common chart values. Formatting functions follow a safe fallback rule: if an input is NaN, Infinity, or cannot be parsed, the function returns the original string as-is instead of printing errors or throwing exceptions.

  • compactNumber(value, locale): Abbreviates large numbers. For example, 1200 becomes "1.2K", 1500000 becomes "1.5M", and 1e12 becomes "1T".
  • currency(symbol?, locale?): Creates a currency formatter. For example, currency('$') can be passed to ChartAxis's tickFormat. Values over 1,000 are automatically abbreviated (such as "$1.5K").
  • percent(value, locale): Formats a decimal ratio as a percentage. For example, 0.45 becomes "45%" and 0.005 becomes "0.5%".
  • shortDate(value, locale): Formats dates as a short month and day. For example, "Jan 5".
  • monthYear(value, locale): Formats dates as month and year. For example, "Jan 2024".
  • formatList(values, locale): Formats a list of words into a natural language string according to locale rules, such as "A, B, and C".

Reduce large line datasets #

m4Reduce groups points by horizontal pixel width and keeps the first, last, minimum, and maximum point in each bucket. It reduces line-rendering work while preserving peaks and valleys that remain visible at the target resolution.

TypeScript
import { m4Reduce } from '@astryx-vue/charts'

const reduced = m4Reduce(rawData, chartWidth, xDomain)

Input data must be sorted by x in ascending order. width is the positive chart width in pixels, and the output contains at most 4 × ceil(width) points. When provided, xDomain should match the chart's x-axis range. Points outside that range join the nearest edge bucket. The function does not mutate input points and returns the original array when the dataset is already small enough.

ParameterTypeDescription
dataM4Point[]{ x, y } points sorted by x in ascending order.
widthnumberPositive pixel width used to create buckets.
xDomain[number, number]Optional x-axis range. Defaults to the first and last x values in the data.

Chart — M4 line reduction

Original12,000 points
M4 reduced · 480 px963 points

Both charts keep the same peaks and valleys. M4 only reduces the number of points.

A line chart comparing 12,000 original points with the M4 reduction while preserving the same major peaks and valleys.

Radial charts #

RadialChart uses a dedicated radial coordinate space. Provide axes for a radar chart, or provide valueKey without axes for a pie or donut chart. Grids, areas, slices, and tooltips share the same center, radii, and angle calculations.

RadialChart propTypeDefaultDescription
dataRecord<string, unknown>[]RequiredSeries rows for radar mode or slice rows for pie mode.
width / heightnumber0 / 400Container width is measured in the browser. Pass width explicitly for SSR.
axesstring[]undefinedRadar axis fields. Providing this selects radar mode.
valueKeystringundefinedNumeric slice field. Non-finite and negative values count as zero.
labelKeystringundefinedSlice label field.
innerRadiusnumber0Inner radius as a fraction of the outer radius. For example, 0.6 creates a donut.
padAnglenumber0.02Angular gap between adjacent slices.
interactivebooleanfalsePrevents page scrolling during touch dragging. When off, pan-y remains available.
labelstringDerived from the modeAccessible SVG name.

Radar charts #

RadialGrid draws concentric polygons and axis lines, RadialArea draws one data row, and RadialAxis draws axis labels. RadialArea.dataKey matches any string field value in a row and falls back to the first row when no match exists.

Vue
<RadialChart :data="data" :axes="['speed', 'handling']" :height="360">
  <RadialGrid :rings="5" />
  <RadialArea data-key="Model A" :color="colors[0]" dots />
  <RadialAxis />
  <RadialTooltip />
</RadialChart>
PropTypeDefaultDescription
RadialGrid.ringsnumber5Number of concentric grid rings.
RadialAxis.labelOffsetnumber16Distance between labels and the outer ring.
RadialArea.dataKeystringRequiredIdentifier of the data row to draw.
RadialArea.colorstringRequiredFill and stroke color.
RadialArea.opacitynumber0.2Fill opacity.
RadialArea.strokeWidthnumber2Polygon stroke width.
RadialArea.dots / dotRadiusboolean / numberfalse / 4Vertex visibility and dot radius.

Chart — Radar chart

Model A Model B

A five-axis radar chart with two series, grid rings, vertex dots, labels, and hover tooltips.

Pie and donut charts #

RadialSlice draws slices from valueKey proportions. A positive innerRadius creates the donut hole. cornerRadius draws real rounded arc geometry. Use labels and labelThreshold to control percentage labels.

Vue
<RadialChart :data="data" value-key="revenue" label-key="region" :inner-radius="0.6">
  <RadialSlice :colors="colors" :corner-radius="4" />
  <RadialTooltip />
</RadialChart>
RadialSlice propTypeDefaultDescription
colorsstring[]RequiredSlice colors, cycled in data order.
cornerRadiusnumber0Corner radius for the inner and outer arc edges.
labelsbooleantrueWhether to show percentage labels.
labelThresholdnumber5Minimum percentage required for a visible label.

Chart — Donut chart

Regional revenue donut with an inner hole, rounded corners, percentage labels, and hover highlighting.

Radial tooltips #

RadialTooltip hit-tests slices by radius and angle in pie mode. In radar mode, it shows the nearest axis and the highest series value on that axis. It supports mouse hover, touch tapping, and dragging. highlight draws and offsets the active slice outline; highlightOffset controls the offset distance.

Use the default slot for custom content. It receives label, value, percentage, and index:

Vue
<RadialTooltip>
  <template #default="{ label, value, percentage }">
    <strong>{{ label }}</strong>
    {{ value }} · {{ Math.round((percentage ?? 0) * 100) }}%
  </template>
</RadialTooltip>

Sankey charts #

SankeyChart represents flow between nodes with ribbons whose width follows the value. Omit columns to infer columns from link direction, or provide string arrays and rich { ids, label } definitions.

A node's value is the total flow through that node. Derive node totals and link values from the same business data so incoming flow, outgoing flow and node totals stay consistent.

Vue
<SankeyChart :nodes="nodes" :links="links" :columns="columns" :min-column-width="180" label="Visitor activation flow">
  <SankeyGrid />
  <SankeyLink color="gradient" :opacity="0.72" />
  <SankeyNode />
  <SankeyLabel />
</SankeyChart>
SankeyChart propTypeDefaultDescription
nodesSankeyNodeDatum[]RequiredNode id, label, total value, and optional OKLCH color.
linksSankeyLinkDatum[]RequiredFlow values between source and target node IDs.
columnsSankeyColumn[]InferredA mixed array of ID arrays or { ids, label } definitions.
width / heightnumber0 / 320Container width is measured in the browser; pass width explicitly for SSR.
nodeWidth / nodeGapnumber20 / 14Node bar width and vertical gap within a column.
nodeColorstringundefinedOne CSS color for every node; labels adapt their contrast color.
minColumnWidthnumber160Minimum column width. Narrow containers scroll horizontally in a keyboard-focusable region.
labelstringLocalizedAccessible name for the SVG and scroll region.

Links, nodes, and labels #

SankeyLink defaults to a source-to-target gradient. color also accepts 'source', 'target', any CSS color, or { gradient: number } with a bias from 0 to 1. tension controls the bezier curve; 0 produces straight ribbons. Gradient IDs are scoped per chart, so multiple charts do not reference each other's definitions.

SankeyNode provides a glow toggle. SankeyLabel chooses rotated on-bar or beside-bar labels from node height; last-column labels anchor left to avoid clipping. Use formatValue for custom values and showPercent for downstream percentages. Percentages use the largest column total as 100%.

PropTypeDefaultDescription
SankeyGrid.dashArraystring'4 4'Column grid dash pattern.
SankeyGrid.color / opacitystring / numberTheme border / 0.3Grid color and opacity.
SankeyGrid.showHeadersbooleantrueShow labels from rich column definitions.
SankeyLink.colorSankeyLinkColor'gradient'Gradient, source, target, or flat color mode.
SankeyLink.opacity / tensionnumber0.7 / 0.5Ribbon opacity and curve tension.
SankeyNode.glowbooleantrueDraw the node glow.
SankeyLabel.showPercentbooleantrueShow percentages for downstream nodes.
SankeyLabel.formatValue(value: number) => stringCompact numberCustom label value formatter.

For up to 100 links, the chart also renders a visually hidden From/To/Value table for screen readers.

Chart — Sankey chart

AcquisitionEngagementOutcomeSearch = 45Direct = 35Social = 20Product = 6060%Docs = 4040%Activated = 5555%Dropped = 4545%
Visitor activation flow data
FromToValue
SearchProduct28
SearchDocs17
DirectProduct22
DirectDocs13
SocialProduct10
SocialDocs10
ProductActivated38
ProductDropped22
DocsActivated17
DocsDropped23

Three columns of visitor flow with gradient ribbons, node labels and headers; narrow screens scroll horizontally.

Three-dimensional SVG charts #

ThreeDChart normalizes x/y/z data, projects it into two-dimensional SVG, and paints marks in depth order. WebGL is not required. With interactive, drag to rotate the camera; when focused, arrow keys rotate by 10° and elevation is clamped from -89° to 89°.

Vue
<ThreeDChart :data="data" x-key="x" y-key="y" z-key="z" interactive>
  <ThreeDGrid />
  <ThreeDAxis />
  <ThreeDScatter color="var(--astryx-color-data-1)" />
</ThreeDChart>
ThreeDChart propTypeDefaultDescription
dataRecord<string, unknown>[]Required3D rows; marks skip rows containing non-finite values.
xKey / yKey / zKeystringRequiredField names for the three dimensions; y is height.
xDomain / yDomain / zDomain[number, number]Data extentOptional explicit numeric domains.
width / heightnumber0 / 400Container width is measured in the browser; pass width explicitly for SSR.
azimuth / elevationnumber35 / 25Initial camera angles in degrees.
interactivebooleanfalseEnable pointer drag and arrow-key rotation, including touch pointer capture.
autoRotatenumber0Azimuth increment per frame; pauses on hover/focus and stops under reduced motion.
labelstringFrom fieldsAccessible SVG name.

Auto-rotation updates about every 50ms and scales by elapsed time. The SVG is focusable when interaction or auto-rotation is enabled. Arrow keys do not move the camera when only auto-rotation is enabled.

Three-dimensional marks #

PropTypeDefaultDescription
ThreeDScatter.colorstringRequiredPoint color; radius and opacity vary with depth.
ThreeDScatter.radius / opacitynumber4 / 0.85Base point radius and opacity.
ThreeDBar.colorstringRequiredFill and stroke for all three bar faces.
ThreeDBar.barWidth / barDepthnumber0.06 / 0.06Width and depth in normalized coordinates, not pixels.
ThreeDGrid.divisionsnumber5Floor divisions along both x and z.
ThreeDAxis.labelsbooleantrueShow field and domain labels.
ThreeDSurface.colorRangestring[]RequiredLow-to-high height color ramp.
ThreeDSurface.opacitynumber0.8Surface fill opacity.
ThreeDSurface.wireframebooleanfalseDraw outlines without face fills.

ThreeDSurface expects a complete x/z grid. Faces with missing cells or invalid points are skipped. All three examples support drag and arrow-key rotation.

Chart — 3D scatter

x [0.9–7.1]y [2.1–7.9]z [0.8–9.2]

Three 3D clusters with a floor grid and axes, supporting drag and arrow-key rotation.

Chart — 3D bars

x [0–6]y [0–10]z [0–4]

3D bars with distinct top, front and side shading.

Chart — 3D surface

x [0–10]y [0–10]z [0–10]

A continuous wave surface colored by height, with guards against missing or invalid cells.

ThreeDScatterGL and other GL/WebGL marks are not included in this package.

Brush selection #

Place <ChartBrush> in the <Chart> interactions slot to let users drag a selection over the plot. mode="x" selects a horizontal range, useful for time windows; mode="xy" selects a rectangle, useful for scatter plots.

Vue
<Chart :data="data" x-key="x" :series="series">
  <template #interactions>
    <ChartBrush @brush="onBrush" @clear="clearSelection" />
  </template>
</Chart>

The brush event receives (range, data). range.x is the [min, max] interval in data coordinates, with range.y also present in xy mode; data contains the original rows inside the selection. clear is a click that did not become a drag.

PropTypeDefaultDescription
mode'x' | 'xy''x'Horizontal or rectangular selection.
colorstringvar(--astryx-color-accent)Selection color.
opacitynumber0.15Selection fill opacity.

Chart — Brush data

Drag across the chart to select a range.

Drag a range and inspect the returned interval and matching rows.

Select data points #

Place <ChartSelect> in the interactions slot to let users click or tap the nearest data point. Pointer positions more than 30 pixels from every point do not trigger a selection.

selected is controlled by the caller and contains data row indices. A regular click selects only the current point. Shift-click or Meta-click toggles that point while preserving the other selected rows.

Vue
<Chart :data="data" x-key="month" :series="series">
  <template #interactions>
    <ChartSelect :selected="selected" @selection-change="selected = $event" />
  </template>
</Chart>

The select event receives (datum, index); selection-change receives the new index array. Selection rings use the chart's resolved point positions and support numeric and categorical x axes.

PropTypeDefaultDescription
selectednumber[][]Selected data row indices.
colorstringvar(--astryx-color-accent)Selection ring color.
radiusnumber6Selection ring radius.

Chart — Select data points

Selected: Feb Use Shift or Meta to toggle multiple points.

Click a data point, or use Shift or Meta to toggle multiple points.

Zoom and pan #

Place <ChartZoom> in the interactions slot to let users zoom with the wheel or a pinch gesture and drag to pan. The top-right toolbar provides zoom in, zoom out, and reset buttons; set toolbar="false" to hide it.

Zoom updates controlled domains through events rather than changing the <Chart> internal state:

Vue
<Chart :data="data" x-key="x" :series="series" :x-domain="xDomain" :y-domain="yDomain">
  <template #interactions>
    <ChartZoom @x-domain-change="xDomain = $event" @y-domain-change="yDomain = $event" />
  </template>
</Chart>

Reset restores the initial domains captured when ChartZoom mounts. A categorical x axis does not participate in numeric zoom or pan. Use xOnly or yOnly to operate on one axis.

PropTypeDefaultDescription
zoomSpeednumber0.1Zoom speed per wheel tick.
xOnlybooleanfalseOperate only on the x axis.
yOnlybooleanfalseOperate only on the y axis.
toolbarfalse | 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left''top-right'Toolbar position or hidden.

Chart — Zoom and pan

x 0.0–15.0 · y 0.0–24.0

Use the wheel or pinch to zoom. Drag to pan. Use the toolbar to reset.

Use the wheel, pinch, drag, and toolbar to adjust the chart range.

Streaming data ranges #

useChartRange manages controlled x/y domains for continuously appended data. Each push(x, y) synchronously updates the ranges. Read them with .value inside <script setup>; template usage unwraps them automatically.

TypeScript
const { xDomain, yDomain, push, reset } = useChartRange({
  xWindow: 300,
  yPadding: 0.1,
})

push(nextX, value)
Vue
<Chart :data="data" x-key="x" :series="series" :x-domain="xDomain" :y-domain="yDomain" />

During warmup, the x domain expands as [0, max(x, 1)]. Once xWindow is reached, it slides as [x - xWindow, x]. By default, y tracks the historical minimum and maximum values observed by the composable. It does not shrink when old points leave the x window. reset() clears that history and restores the initial ranges.

OptionTypeDefaultDescription
xWindownumberRequiredWidth of the sliding x window.
yDomain[number, number]undefinedFixed y domain. Providing it disables automatic tracking.
yPaddingnumber0.1Padding ratio added above and below the automatic y range.
yCenterbooleanfalseExpands the automatic y domain symmetrically around zero.

Chart — Streaming data ranges

x 9–109 · y 0.9–23.6 · 101 points

Start adds one point every 450 ms. The x window slides and y tracks the observed range.

Start and pause streaming or reset the chart to inspect controlled x/y domain changes.

Accessibility #

Charts include built-in accessibility features so screen reader users can understand chart content:

  • The root element has a role="img" attribute.
  • The chart's accessible name prioritizes the title prop. When title is omitted, the component builds a semantic description from primary series and the x-axis field (such as "Monthly Revenue and Cost trend"). If only annotations are present, it falls back to "Chart".
  • The subtitle prop maps to the chart's accessible description.
  • When total data points (data rows × data columns) do not exceed 100 (MAX_TABLE_POINTS), the chart generates a visually hidden data table using VisuallyHidden. Screen readers can read exact values row by row. Above 100 points, the table is omitted to prevent excessive speech noise.

Server-side rendering #

During server-side rendering (SSR), no browser DOM exists, so the component cannot measure parent container width in pixels.

When rendering on the server, pass an explicit width prop on <Chart>. This allows the server to compute scales and render complete SVG paths and rectangles into HTML. After client-side hydration, once the browser measures the real container width, the chart takes over and responds to container resize events.

Not supported yet #

To stay lightweight and focused, the package currently leaves out:

  • Four WebGL-based series marks for very large datasets (such as dotGL) are not yet included.
  • The Nuxt module does not yet include auto-import switches for @astryx-vue/charts. Import components manually when using Nuxt.