Skip to content

Time Series

/assets/charts/examples/line/line-chart-time-series.js

Time Series is the chart for long date-based series where the main problem is navigation, not drawing a line. Price history, balances, revenue, traffic, sensor data: the moment the dataset stops fitting into one comfortable view, you need a way to switch windows without rebuilding the chart by hand.

In RareCharts, this module combines three things:

  • a main line chart for the active date window
  • a range bar with preset buttons, if you enable timeframes
  • a navigator strip with a brush, if you enable navigator

The important bit is that both the buttons and the brush work with the same internal view. If the user clicks a range button, the chart updates its visible extent. If the user drags the brush, the chart updates the same visible extent. No duplicated state, no two widgets trying to outsmart each other, no “why is the UI lying to me” moment.

RARE — —
OPEN
—
HIGH
—
LOW
—
VOLUME
—

What problem it solves

The plain Line chart is enough when one view is enough. TimeSeries exists for the next step: when you want one chart instance to support “show me the last month”, “show me the last year”, and “show me everything” without wiring a second component tree around it.

This example uses:

  • preset range buttons: 1M, 3M, 6M, 1Y, 2Y, ALL
  • a built-in navigator strip under the chart
  • a custom tooltip
  • a few stats below the chart

Only the first two are specific to the module. The tooltip and stats are just ordinary page code around it.

Range buttons

Range buttons are controlled by the timeframes option.

const chart = new RareCharts.TimeSeries('#chart', {
  timeframes: true,
  defaultTimeframe: '1Y',
});

timeframes: true enables the built-in preset set: 1M, 3M, 6M, 1Y, 2Y, ALL. If you need a custom set, pass an array instead.

So:

  • if you omit timeframes, there is no range bar
  • if you pass timeframes: true, you get the built-in preset set
  • if you pass ['1Y', 'ALL'], you get exactly those two buttons

The gray strip under the chart is controlled by navigator.

const chart = new RareCharts.TimeSeries('#chart', {
  navigator: true,
});

Or with options:

const chart = new RareCharts.TimeSeries('#chart', {
  navigator: {
    height: 56,
    color: '#666666',
    area: 1,
    areaColor: '#cccccc',
  },
});

If enabled, the navigator always reflects the full dataset and highlights the current view. Dragging the brush updates the main chart; when the drag ends, onViewChange reports the new window, as a range button does. A click on the strip without a drag keeps the current selection. Clicking a range button also updates the brush. The strip lines up with the plot area (its side margins follow the chart's); pass margin: { left, right } to set them, and area: false to draw the line alone. Same state, two controls, fewer bugs.

Programmatic control

The visible window is part of the chart API.

const chart = new RareCharts.TimeSeries('#chart', { timeframes: true }).setData(data);

chart.setView([new Date('2025-01-01'), new Date('2025-06-30')]);
chart.setTimeframe('3M');   // as a click on the 3M button
const current = chart.getView();

chart.onViewChange(extent => {
  console.log(extent);
});

This matters when the date range is driven by router state, saved user settings, query params, or another piece of UI that insists on being in charge.

Logarithmic scale

For prices that span decades, set yScale: 'log': ticks fall on powers of ten, the margin above and below is a factor of the data's span, and zero or negative points are skipped with one console warning. scaleToggle: true adds a Log toggle to the top right of the header, filled while the axis is logarithmic, above the Y-axis labels — the range buttons keep their place; setYScale('log' | 'linear') switches from code, and onScaleChange(fn) reports every switch. The scale is the same as on Line.

const chart = new RareCharts.TimeSeries('#chart', {
    timeframes: true,
    yScale: 'log',
    scaleToggle: true,
});

chart.onScaleChange(({ scale }) => console.log(scale));

Custom ranges

If the built-in shortcuts are not enough, you can define your own buttons.

const end = data[data.length - 1].date;

timeframes: [
  'ALL',
  {
    key: 'SINCE_2025',
    label: 'Since 2025',
    range: [new Date('2025-01-01'), end],
  },
  {
    key: 'SINCE_2026',
    label: 'Since 2026',
    range: [new Date('2026-01-01'), end],
  },
]

Rules:

  • ALL means the full data extent
  • built-in string shortcuts such as 1M, 6M, 1Y, YTD, ALL are resolved by the chart
  • custom buttons use { key, label, range }
  • range is [start, end]
  • the final range is clamped to the real data extent, so overshooting the dataset is safe
  • if multiple buttons resolve to the same final extent, the button chosen last stays active — clicked or set with setTimeframe(), or defaultTimeframe while its view holds; without one (before any selection, or after a brush drag, Ctrl/⌘ + wheel or setView, which clear it) a view of the whole data lights ALL (or MAX), any other the first matching button in the list

Analytics ranges

A traffic or sales report counts its windows from now: "today", "this week", "this month". Set timeframeAnchor: 'now' and use the calendar keys:

/assets/charts/examples/line/line-chart-traffic.js

const chart = new RareCharts.TimeSeries('#chart', {
    timeframeAnchor: 'now',
    timeframes: [
        { key: 'TODAY', label: 'Today' },
        { key: 'WTD',   label: 'Week' },
        { key: 'MTD',   label: 'Month' },
        { key: 'YTD',   label: 'Year' },
        { key: 'ALL',   label: 'All time' },
        { key: 'CUSTOM', label: 'Custom' },
    ],
    compare: 'previousPeriod',
    yFormat: 'number',
    gaps: 'zero',
    navigator: true,
}).setData({ hour, day, month });   // levels: see Resolution below

timeframeAnchor is the end every timeframe counts back from:

  • 'dataEnd' (the default) — the last data point, as before;
  • 'now' — the current moment. It is read when the data is set, a point appended or a button clicked, and kept across resizes. A page that wants a moving "now" calls setData or setTimeframe again;
  • a date — a fixed "as of" instant (a Date, epoch ms or an ISO string with a time; a date-only string is that day's midnight).

With an anchor past the data, ALL, the zoom and the navigator run on to it; a window still starts no earlier than the data.

Key Window
ALL / MAX the whole data
TODAY from the start of the anchor's day
WTD from the start of the anchor's week (weekStart: Monday by default, 'sunday' or a number 0–6)
MTD from the start of the anchor's month
YTD from the start of the anchor's year
24H, nH n real hours back, so 24H across a daylight-saving change is 24 hours while that day is 23 or 25
7D, 3M, 1Y… n calendar days, weeks, months or years back

Every window ends at the anchor and is cut in the chart's timeZone. The keys, the anchor and the custom range below work on every chart with timeframes; see Settings.

Custom range

'CUSTOM' in timeframes adds a "Custom" button (the page's label wins). It opens a small panel with From and To date fields and Apply:

  • the fields start at the days in view and stay within the data's days; To before From swaps them; an empty field disables Apply;
  • Apply shows whole days in the chart's zone, from midnight of From to the end of To;
  • Enter applies; Escape or a click outside closes the panel and returns focus to the button;
  • the chart keeps the days: setData and appendPoint show the same dates again, and the button stays pressed while that view holds (its title names the days). The brush, the wheel and setView release it.

From code: chart.setTimeframe('CUSTOM', { range: ['2026-03-01', '2026-03-31'] }). The panel is styled by the library itself (.rc-range-panel), so it looks the same with or without Rare Styles on the page.

Resolution follows the window

A year of hourly rows is too many to draw, and a day of daily rows is one point. Hand the chart the same series at several bucket sizes — the server aggregates, the chart never sums — and it draws, for each window, the finest level that fits:

chart.setData({
    hour:  [{ date: '2026-11-18T14:00', value: 312 }, …],   // the last weeks only is fine
    day:   [{ date: '2026-11-18', value: 4120 }, …],
    month: [{ date: '2026-11', value: 98200 }, …],
});
  • level keys: minute, hour, day, week, month, quarter, year. Each row is dated at the start of its bucket in the chart's zone;
  • resolution: { maxPoints: 500 } — for a window, the finest level that covers it (one bucket of slack at each end) with at most maxPoints rows; if none fits, the coarsest one that covers it;
  • the full range is the union of the levels; the navigator draws the coarsest level (navigator: { level: 'day' } picks another);
  • getLevel() names the level drawn; appendPoint(point, 'hour') adds to a level;
  • the tooltip names the date by the bucket: Nov 18, 2026, 14:00, Nov 18, 2026, Week of Nov 16, 2026, November 2026, Q4 2026, 2026.

Loading on demand. A level may cover only part of the time. To fetch finer rows when the window asks for them:

chart.onViewChange(async (extent, { key, level }) => {
    if (level !== 'month') return;
    chart.setLoading(true);                        // a slim "Loading…" bar over the plot
    const day = await fetchDays(extent);
    chart.setData({ ...levels, day }).setLoading(false);
});

The window and the selected button hold across setData, and setData itself reports no view change. Under gaps: 'zero' a level must have no unloaded holes inside its rows: the fill would count them as zeros.

Comparison with an earlier period

compare: 'previousPeriod' draws the same metric for an earlier window over the current one, as a grey dashed line under the main line; compare: 'previousYear' always compares with a year before.

The view was set by Compared with
TODAY, WTD, MTD, YTD the day, week, month or year before — the same days: 1–18 November against 1–18 October
nH, nD, nW, nM, nY the n before
Custom as many days before
the brush, the wheel or setView, after one of the above the same as that period: zoomed into a week, still the week before, so the two lines keep their rhythm
ALL, or nothing picked its own length before, in whole days (whole hours under a day)

Each row is moved on its own, so months line up day by day; two rows that land on one date keep the later one. The comparison uses the rows of the level drawn. The default tooltip adds a row such as Previous period 1,100 · Oct 18 · +12.2%. The Y axis fits both lines; the time axis and the navigator follow the main one.

The comparison is a second legend key, named by compareName (default "Previous period" or "Previous year"): legend: [{ label: 'Visits' }, { label: 'Previous period' }] with seriesName: 'Visits' makes both toggles, and the comparison's item gets a dashed swatch. compareColor recolours it.

A hidden series leaves the line, the area and the crosshair; with nothing shown the frame stays — axes, grid, annotations — and the crosshair is off. The Y axis fits the series shown; the time axis, the view, the timeframes and the navigator never follow the legend. setSeriesVisible(names | null) sets it from code. More: Interactive legend.

Counts and gaps

The default Y format is money, as before ($1,234). For counts set yFormat: 'number': the ticks are compact, as on Line (1.2k), and the tooltip shows the exact number (1,234). yPrefix and ySuffix dress both formats.

gaps says what a missing bucket is:

  • 'join' (default) — the line joins its neighbours, as before;
  • 'zero' — it is drawn as 0. Nothing is filled before the first row; with timeframeAnchor: 'now' the buckets after the last row are filled up to now;
  • 'break' — the line and the area stop there; a lone point gets a dot, and the tooltip over the gap says "No data".

With 'zero' or 'break', a row whose value is null is a missing bucket too. The bucket comes from the level, or from interval ('hour', 'day', 'week', 'month'…), or from the data's most common step. On a log scale 'zero' draws as 'break'.

Bands

band: true draws a ribbon between the rows' lower and upper fields, under the area and the line — a forecast range, a min–max envelope. band: { lower: 'p10', upper: 'p90', name: 'P10–P90' } names the fields; color and fillOpacity (0.12) restyle it. A row without both edges breaks the ribbon. The Y axis fits it, the tooltip adds Range 90 – 110, and its name is its legend key. The same ribbon on several series lives on Line and Dual Axes.

Zoom and pan

Ctrl (⌘ on a Mac) + the mouse wheel, or a trackpad pinch, zooms; a drag pans. A plain wheel scrolls the page and shows "Hold Ctrl to zoom" for a moment. On a phone one finger scrolls the page and two fingers pan and pinch the chart; the navigator's brush still takes one finger.

Annotations

Time Series supports event markers and reference levels via the annotations option — useful for marking halvings, earnings dates, or product releases on a long-running price feed, and for placing horizontal levels (break-even, cost basis, target) on top of the area. Annotations stay in sync with zoom and pan: out-of-range entries are skipped, range bands are clamped to the visible window. See the dedicated annotations page for the full API.

Time Series chart options

Common options shared by all chart types (title, subtitle, legend, legendPosition, source, note, controls, theme) are documented on the Settings page.

Option Type Default Description
Layout
height number 340 Chart height in px.
margin object — Inner padding {top, right, bottom, left}. Defaults { top: 16, right: 70, bottom: 28, left: 0 }; hidden axes give their gutters back, and annotations raise top to annotationLabelHeight + 4 unless you set margin.top.
timeZone string 'local' 'local' or 'UTC': the zone a date string without a zone of its own is read in (the rows, annotations, the view bounds), the timeframes cut in, and the axis and the tooltip name dates in. A Date, epoch milliseconds or an ISO string with Z or an offset stays that instant. See Dates and time zones.
timeframes boolean | array — Range bar button definitions. Pass true to use the built-in preset set ['1M', '3M', '6M', '1Y', '2Y', 'ALL']. Or pass an array of built-in shortcuts and custom objects with key, label, and range.
defaultTimeframe string | object — Initial active timeframe used on first render when no explicit view has been set.
defaultView array — Initial visible date range as [from, to]. An explicit alternative to defaultTimeframe; clamped to the data extent. If it misses the data, the chart shows the full range; set together with defaultTimeframe, defaultView wins.
timeframeAnchor 'dataEnd' | 'now' | date 'dataEnd' The end every timeframe counts back from: the last data point, the current moment, or a fixed instant. With an anchor past the data, ALL, the zoom and the navigator run on to it. See Analytics ranges.
weekStart string | number 'monday' The first day of a week for WTD and week buckets: a day name or 0–6 (0 is Sunday).
navigator boolean | object — Built-in overview strip under the chart. Pass true for defaults or an object with options such as height, color, area, areaColor, brushColor, margin (defaults to the chart’s side margins, so the strip lines up with the plot) and axis (a time axis under the strip). With levels, level picks the level the strip draws (the coarsest by default).
Axes
xTickFormat function by span (date) => string — formats X axis labels. The default follows the span in view: '%H:%M' up to 36 hours (a tick at midnight names the day), '%b %d' up to 92 days (at most one tick per day), '%b' up to a year, "%b '%y" up to five years, '%Y' beyond — so a 1M view reads days and a long one names its years.
yTickFormat function by yFormat (value) => string — formats Y axis labels.
yFormat 'currency' | 'number' 'currency' 'currency': $1,234 on the axis, $1,234.56 in the tooltip. 'number': compact ticks as on Line (1.2k) and the exact count in the tooltip (1,234).
yPrefix / ySuffix string '$' / — Text around the default labels; the prefix is '$' under 'currency' and empty under 'number'.
yScale 'linear' | 'log' 'linear' Y scale type. 'log': power-of-ten ticks, multiplicative margin, values ≤ 0 skipped. Switch with setYScale().
scaleToggle boolean | object false A Log toggle pinned to the top right of the header, above the Y-axis labels: filled while the axis is logarithmic, transparent while it is linear; a click flips the scale. true or { labels: { log } }, labels.log being its text. Each switch fires onScaleChange.
yTicks number 5 Y axis tick count.
yTickValues array — Explicit Y tick positions. Overrides automatic tick generation; the value range widens to include them.
yLabelsOnly boolean true Show only Y labels and suppress the axis line.
Visibility
showGrid boolean true Show horizontal grid lines.
showXAxis boolean true Show the X (date) axis at the bottom. Hiding it also collapses the bottom margin, so the plot runs flush.
showYAxis boolean true Show the Y (price) axis on the right. Hiding it also collapses the right margin. An explicit margin always wins.
Line and Area

The line takes theme.accent and theme.strokeWidth (2px) — set them through theme.

curve string 'monotone' D3 curve type: 'linear', 'monotone', 'basis', 'cardinal', 'step', 'stepBefore', 'stepAfter'.
curveTension number 0 0–1, the tension of 'cardinal', as on Line.
area boolean | number true Area fill under the line. true uses a gradient, a number is treated as solid fill opacity, and false disables the area.
areaColor CSS color theme accent Area fill color.
Analytics
resolution object { maxPoints: 500 } With levels (setData({ hour, day, month… })), the most rows a window may draw: the finest level that covers the window within it is drawn. See Resolution.
gaps 'join' | 'zero' | 'break' 'join' A missing bucket joins its neighbours, is drawn as 0, or breaks the line (a lone point gets a dot, the tooltip says “No data”). Under 'zero' / 'break' a null value is a missing bucket.
interval string from the data The bucket of plain rows: 'minute', 'hour', 'day', 'week', 'month', 'quarter' or 'year'. It sets what a missing bucket is and how the tooltip names a date; without it, the data's most common step.
compare false | 'previousPeriod' | 'previousYear' false A grey dashed line of an earlier window over the current one; the tooltip adds its value and the change. See Comparison.
seriesName string 'Series' The series' name and legend key: legend: [{ label: 'Visits' }] with seriesName: 'Visits' makes the item a toggle.
compareName string 'Previous period' The comparison's name and legend key ('Previous year' for 'previousYear').
compareColor string theme muted The comparison's colour.
band boolean | object — A ribbon between the rows' lower and upper fields; { lower, upper, name, color, fillOpacity } names the fields and styles it (name 'Range', opacity 0.12).
Interaction
tooltipFormat function — (point, info) => html — custom tooltip for the active point: point is the row, with its extra fields; info is { date, value, color, level }, plus series and compare ({ date, value, change } or null) with compare, and band ({ lower, upper } or null) with band (formatter arguments). Not called over a gap. The default shows the date, named by the bucket, and the value in the chart's format.
crosshair boolean true Crosshair lines and the tooltip on hover; false turns both off.
Annotations
annotations array — Event markers and reference levels. Vertical (date, from/to) and horizontal (value, yFrom/yTo) entries are mixed in the same array. Stay in sync with zoom and pan. See Annotations.
annotationLabelHeight number 22 Pixels reserved above the chart for vertical annotation labels.

Time Series instance methods

Method Signature Description
setData (data | levels) Sets the full dataset and re-renders. The chart keeps a sorted copy: date may be a Date, an ISO string or epoch ms, value a number or a numeric string; unreadable rows are dropped; other fields (open, volume…) reach tooltipFormat. A selected timeframe re-applies to the new data; a window the new data no longer reaches falls back to the default view. levels is { minute, hour, day, week, month, quarter, year }, each an array of rows (Resolution).
appendPoint (point, level?) Adds one point (read like setData) to the chart’s copy, keeps it in date order, and re-renders. A selected timeframe moves with the new point. The array passed to setData is not modified. With levels, it adds to level (the finest without one).
setView ([start, end], { silent? }) Sets the visible date window and returns the chart. A window outside the data shows an empty plot; setView(null) goes back to defaultView / defaultTimeframe / the full range. { silent: true } skips onViewChange.
setTimeframe (key, { silent?, range? }) Applies a timeframe — a key of timeframes or a preset such as '1Y' — as its button does, and highlights the button. setTimeframe('CUSTOM', { range: [from, to] }) sets the custom range. Returns the chart.
getView () Returns the current visible date window.
onViewChange (fn) Registers fn(extent, { key, level }), run whenever the visible date window changes: a range button, setView, Ctrl/⌘ + wheel, or the end of a navigator drag. key is the timeframe key when a button or setTimeframe set the window, else null; level the level drawn, or null for plain rows.
getLevel () The name of the level drawn, or null for plain rows.
setLoading (on = true) Shows or hides a slim “Loading…” bar over the plot and sets aria-busy on the card; the drawing stays until new data comes. Returns the chart.
setYScale (type, { silent? }) Switches the Y scale to 'log' or 'linear', redraws and fills or clears the Log toggle. Returns the chart.
onScaleChange (fn) Registers a callback that gets { scale, axis: 'y' } whenever the scale switches (the Log toggle or setYScale without silent).

Overview (standalone navigator)

RareCharts.Overview is the strip the navigator option builds, as a class of its own: a small line of a series with a brush for picking a date window. Use it when the strip and what it drives are apart — a chart in another card, a table, several charts at once. It is not a chart: no header, footer, timeframes or whenReady(), and new Overview(…) draws nothing until setData.

const overview = new RareCharts.Overview('#overview', { height: 56 });

overview.setData(data, extent => chart.setView(extent));
chart.onViewChange(extent => overview.setBrush(extent));

Dates are read as the charts read them — a Date, an ISO string or epoch milliseconds — in the rows, in extent and in setBrush. The strip keeps a sorted copy of the rows; a row with an unreadable date or value is dropped.

Option Type Default Description
height number 52 Height of the strip in pixels, its margins included.
color CSS color theme border Line color.
area boolean | number true Fill under the line: true a gradient, a number a solid fill at that opacity, false none.
areaColor CSS color theme accent Fill color.
brushColor CSS color theme text Outline and handles of the selection.
margin object { top: 6, right: 70, bottom: 16, left: 0 } Space around the line; a side you leave out keeps its default. The right 70 lines the strip up with the Y-axis gutter of the charts it sits under.
axis boolean false A time axis under the strip.
timeZone string 'local' 'local' or 'UTC': the zone date strings without a zone are read in — the rows, extent, setBrush() — and the axis names dates in. Under a chart the strip takes the chart's zone.
ariaLabel string 'Chart' The accessible name of a standalone strip, whose <svg> gets role="img". Under a chart the strip is part of the chart's drawing and takes no name of its own.
theme object default theme A theme or overrides, merged as a chart's theme is (createTheme: tooltip and map deeply) — RareCharts.darkTheme on a dark page. The element gets the class rc-overview, which carries the chart tokens, so a standalone Overview follows the page's --chart-* as a chart does.
Method Signature Description
setData (data, onBrush, { extent }?) Draws data, rows of { date, value }. onBrush(extent, { final }) runs while the selection is dragged, with [start, end] as Dates; final is true once, when the drag ends. extent is the span of the strip, the data’s own by default — pass the full span of the chart, so dates that only its other series cover can be brushed to. Returns the strip.
setBrush ([start, end]) Moves the selection to that window, clamped to the strip, without calling onBrush. Does nothing before setData or for a bound that is not a date.
destroy () Removes the strip and stops watching the container’s size. onBrush is never called after it, not even for a drag already under way.