Skip to content

Timeline

Creates an interactive timeline brush component for selecting time periods within a visualization.

With brushing: false, the timeline selects a single period across the domain; enabling playButton adds controls to step through the periods automatically.

Determines the visibility of the play button to the left of the timeline, which cycles through the available periods at a rate set by playButtonInterval.

With brushing: true, viewers can drag to select a time range instead of a single period.

The timeline is an Axis, so ticks chooses which periods get a mark and tickFormat rewrites their labels; abbreviating the years keeps a long range readable at a narrow width.

const config = {
  domain: [2000, 2020],
  height: 100,
  tickFormat: d =>
    `'${String(d instanceof Date ? d.getFullYear() : d).slice(-2)}`,
  ticks: [2000, 2004, 2008, 2012, 2016, 2020],
  width: 520,
};

selection sets the range (or single period) that is highlighted before the viewer touches anything, and snapping: false lets the brush handles rest between ticks instead of jumping to the nearest period.

Toggles the snapping value.

The minimum number of ticks (or buttons) a selection can span. Helpful for x/y plots where selecting fewer than 2 time periods is undesirable. A narrower brush widens to it on release: a drag keeps the end being dragged (or, with ticks, its first tick), and a click selects the clicked period and the ones after it. A narrower starting selection keeps its latest period, and a chart that starts on its latest period starts on its latest brushMin instead. Either way, the selection grows the other way where the timeline runs out. Unused with brushing: false.

brushMax caps how many ticks a selection can span. Drag across more and the brush is pulled in on release, keeping the end you dragged; a wider starting selection keeps its latest periods. brushMin sets the fewest the same way, with ticks or buttons: a narrower brush widens, and a click selects that many periods from the one clicked. On a chart, pass both through timelineConfig. When brushMin is larger, brushMin wins.

The maximum number of ticks (or buttons) a selection can span; unlimited by default. A wider brush is pulled in to it on release, keeping the end being dragged, and a wider starting selection keeps its latest periods. A brushMax below brushMin rises to it.

The minimum number of ticks (or buttons) a selection can span. Helpful for x/y plots where selecting fewer than 2 time periods is undesirable. A narrower brush widens to it on release: a drag keeps the end being dragged (or, with ticks, its first tick), and a click selects the clicked period and the ones after it. A narrower starting selection keeps its latest period, and a chart that starts on its latest period starts on its latest brushMin instead. Either way, the selection grows the other way where the timeline runs out. Unused with brushing: false.

A chart with time starts on its latest period. Its timeFilter starts it somewhere else: the chart draws the rows it keeps, and its timeline selects their periods. Once the viewer picks another period, that pick replaces the filter. timelineDefault (a date, or the first and last of a range) and timelineConfig.selection start a chart the same way.

const sales = ["Apples", "Pears", "Plums", "Figs"].flatMap((fruit, i) =>
  Array.from({length: 10}, (_, y) => ({
    fruit,
    year: 2015 + y,
    sales: 30 + ((i * 7 + y * 5) % 11) * 8,
  })),
);

const config = {
  data: sales,
  groupBy: "fruit",
  sum: "sales",
  time: "year",
  timeFilter: d => d.year === 2019,
};

timelineConfig.on.end runs whenever the viewer clicks, drags or plays the timeline to a new period, and receives what they picked: a Date for one period, or [start, end] Dates for a range. Here it rewrites the subtitle, which the chart draws again with the new period. on.brush receives the selection while a drag is still moving.

const sales = ["Apples", "Pears", "Plums", "Figs"].flatMap((fruit, i) =>
  Array.from({length: 10}, (_, y) => ({
    fruit,
    year: 2015 + y,
    sales: 30 + ((i * 7 + y * 5) % 11) * 8,
  })),
);

// `on.end` receives a Date for one period, or [start, end] for a range.
const years = period => [].concat(period).map(d => new Date(d).getFullYear());

let picked = "2020–2021";

const config = {
  data: sales,
  groupBy: "fruit",
  sum: "sales",
  time: "year",
  timelineDefault: ["2020", "2021"],
  subtitle: () => `You picked ${picked}`,
  timelineConfig: {
    on: {
      end: period => {
        const [first, last] = years(period);
        picked = first === last ? `${first}` : `${first}–${last}`;
      },
    },
  },
};

brushCursor sets the cursor over the brush area, "pointer" by default: a CSS cursor, or a function given how the timeline is drawn ("ticks" or "buttons"). The handles keep their resize cursor; handleConfig and selectionConfig take a cursor to change those too.

buttonBehavior: "auto" draws buttons when every label fits and ticks when they don’t, and checks again each time the chart redraws, such as after a resize. The timeline’s group names the result in a class, so page CSS can follow it: a chart’s g.d3plus-viz-timeline also carries d3plus-viz-timeline-ticks or d3plus-viz-timeline-buttons, and a Timeline’s own group d3plus-Timeline-ticks or d3plus-Timeline-buttons.

g.d3plus-viz-timeline-buttons .selection {
fill-opacity: 0.5;
}
buttonBehavior

How the timeline draws its periods: "ticks" along an axis, "buttons" in a row, or "auto" (the default), which draws buttons when every label fits and ticks otherwise, and checks again whenever the chart redraws. The timeline's group carries a class naming the result, for page CSS: d3plus-viz-timeline-ticks or d3plus-viz-timeline-buttons on a chart's g.d3plus-viz-timeline, and d3plus-Timeline-ticks or d3plus-Timeline-buttons on the Timeline's own group.

Configuration

import {Timeline} from "@d3plus/core";

Extends Axis → BaseClass.

alignstringDefault middle
barConfigrecord

Axis line style.

baselinenumberDefault 0

The tick the axis's baselineBreak returns to. Defaults to 0. To start a Plot's value axis at a value, set the chart's baseline instead.

baselineBreakbooleanDefault false

When a linear value axis's domain stops short of the baseline (e.g. [1100, 2100] with a baseline of 0), keeps the baseline tick and breaks the axis between it and the domain, styled by baselineBreakConfig. Turned off, a Plot's yDomain stretches to the baseline instead. Defaults to true for Plots whose marks grow from 0 (BarChart, AreaPlot, Histogram, Lollipop), else false.

baselineBreakConfigrecord

Style of the break drawn when baselineBreak is on and the domain stops short of baseline: space (pixels of axis between the baseline tick and the first tick after the break), gap (pixels between the two break marks, where the axis line is not drawn), size (length of each mark, drawn outward from the axis line on the tick side so it never reaches into the plot), angle (degrees each mark tilts from perpendicular), lines and lineConfig (the lines a Plot runs across the plot from each mark, as in breakConfig), mask (whether a Plot cuts the gap between those lines across the shapes, default true), plus stroke/stroke-width and other line styles for the marks.

breakfalse | [number, number] | array.<[number, number]>Default false

Value ranges to remove from a linear axis: one [start, end] pair or a list of them. Each collapses to a short marked gap (styled by breakConfig); values either side share one scale, and tooltips still show real values. Ranges outside the domain are ignored.

breakConfigrecord

Style of the breaks set with break: space (pixels of axis each break occupies), spaceMin (the least space a break shrinks to when the axis is too short to hold space and leave twice that for the data; by default such a break is dropped), gap (pixels between its two marks, where the axis line is not drawn; it shrinks with the break), size (length of each mark, drawn outward from the axis line on the tick side so it never reaches into the plot), angle (degrees each mark tilts from perpendicular), lines (whether a Plot runs a line across the plot from each mark, default true), lineConfig (those lines' style — stroke, stroke-width, … — over the axis line's barConfig style), mask (whether a Plot cuts the gap between the lines across the shapes, default true), plus stroke/stroke-width and other line styles for the marks.

brushCursorstring | functionDefault pointer

The cursor shown over the timeline's brush area, where a click or drag picks periods: a CSS cursor, or a function given how the timeline is drawn ("ticks" or "buttons") that returns one. Defaults to "pointer". The handles keep ew-resize and the selected range move; handleConfig and selectionConfig take a cursor too.

brushFilterfunction

Brush event filter.

brushMaxnumber

The maximum number of ticks (or buttons) a selection can span; unlimited by default. A wider brush is pulled in to it on release, keeping the end being dragged, and a wider starting selection keeps its latest periods. A brushMax below brushMin rises to it.

brushMinnumber

The minimum number of ticks (or buttons) a selection can span. Helpful for x/y plots where selecting fewer than 2 time periods is undesirable. A narrower brush widens to it on release: a drag keeps the end being dragged (or, with ticks, its first tick), and a click selects the clicked period and the ones after it. A narrower starting selection keeps its latest period, and a chart that starts on its latest period starts on its latest brushMin instead. Either way, the selection grows the other way where the timeline runs out. Unused with brushing: false.

brushingbooleanDefault true
buttonAlign"start" | "middle" | "end"Default middle

Toggles the horizontal alignment of the button timeline.

buttonBehavior"auto" | "buttons" | "ticks"Default auto

How the timeline draws its periods: "ticks" along an axis, "buttons" in a row, or "auto" (the default), which draws buttons when every label fits and ticks otherwise, and checks again whenever the chart redraws. The timeline's group carries a class naming the result, for page CSS: d3plus-viz-timeline-ticks or d3plus-viz-timeline-buttons on a chart's g.d3plus-viz-timeline, and d3plus-Timeline-ticks or d3plus-Timeline-buttons on the Timeline's own group.

buttonHeightnumberDefault 24

Button height.

buttonPaddingnumberDefault 10

Button padding.

classNamestring | array.<string> | undefined

CSS classes added to the outermost element this chart or component draws into, next to its fixed d3plus classes, so page CSS can target it: a chart's root <svg class="d3plus-viz"> (its <canvas> with the Canvas renderer) and a standalone component's <svg>. Takes a space-separated string or an array. A new value replaces the classes the previous one added; unset adds none. Tooltips take their own tooltipConfig.className.

colorDefaultscolordefaultsconfig

Overrides the default colors used when assigning fills from data and choosing legible text colors: dark and light (the text colors picked for contrast against a background), missing (null/undefined values), on/off (true/false values), sequential (the anchor hue for magnitude ramps), and scale (the categorical palette, given as a d3 ordinal scale or an array of colors). Keys are merged into the current defaults, and a Viz passes its overrides down to the shapes and components it draws.

configd3plusconfig

Methods that correspond to the key/value pairs and returns this class.

dataarray.&lt;unknown&gt;

An array of data points, which helps determine which ticks should be shown and which time resolution should be displayed.

domainarray.&lt;string | number | date | undefined&gt;Default [0,10]

The axis's domain: [min, max] on a continuous axis, or the categories to show on a discrete one. In a Plot it overrides xDomain/yDomain and isn't rounded unless rounding says so; a single end ([min] or [undefined, max]) pins that end like yDomain([min]).

domainTicksbooleanDefault true

Whether the domain's min and max are always shown as ticks, even when they aren't among the scale's own "nice" tick values (the nearest nice tick is dropped when it would crowd them). Defaults to true; zooming turns it off so a rescaled axis shows only nice values.

durationnumberDefault 600

Animation duration in ms.

exponentnumberDefault 1

The exponent of a "pow" axis (scale: "pow"): below 1 it spreads the small values out and squeezes the large ones together (0.5 matches a "sqrt" axis), above 1 it does the opposite. Defaults to 1, which draws like a linear axis. Only a "pow" axis reads it; on any other scale it has no effect, and a value that isn't a positive number falls back to 1. Ticks are spaced evenly along a power axis and rounded to round values.

fixedSizenumber

Exact size of the space that contains the axis tick labels and title. Labels that need more room overflow outward instead of moving the axis line; zooming pins a rescaled axis this way so it doesn't shift.

gridarray.&lt;unknown&gt;

Grid values of the axis.

gridConfigrecord

Grid config of the axis.

gridLogbooleanDefault false
gridSizenumber

Grid size of the axis.

handleConfigrecord

Handle style.

handleSizenumberDefault 6

Handle size.

heightnumberDefault 400

Overall height of the visualization in pixels.

labelOffsetfalse | numberDefault false
labelRotationnumber | boolean | undefined

Whether to rotate the axis labels, and by how much. true rotates them -90 degrees and false keeps them flat. Left undefined (the default), a horizontal axis of categories rotates its labels when any label would not fit its share of the axis whole (a word dropped, cut off, or broken across lines) or would overlap its neighbor: they slant 30 degrees (-30 on a bottom axis, 30 on a top one), or stand at -90 when even slanted they would leave more labels cut short or hidden. A vertical axis never rotates its labels on its own. A number rotates them by that many degrees (clockwise, so -45 rises to the right): each label hangs off the axis from the end of its text nearest the axis, which sits across from its tick, so on a bottom axis a negative angle ends each label at its tick and a positive one starts it there. Angles outside -90 to 90 turn a half turn to read left to right (135 draws as -45), and 0 keeps the labels flat. Slanted labels wrap between words onto up to three lines, as many as fit between neighboring labels, so they reach less far from the axis. Labels that still overlap once rotated are thinned evenly.

labelsarray.&lt;unknown&gt;

Visible tick labels of the axis. Also takes a list of label lists, from the most labels to the fewest: the axis labels the first list whose labels all fit whole without crowding, else the last one, thinned. Its ticks then follow the chosen list unless ticks is set.

localestring | object

The locale used for all text and number formatting. Supports the locales defined in d3plus-format. The locale can be a complex Object, a locale code (like "en-US"), or a 2-digit language code (like "en"). If a 2-digit code is provided, the "findLocale" function is used to identify the most approximate locale.

maxSizenumber | function

Maximum size allowed for the space that contains the axis tick labels and title: a number of pixels, or a function that is given the room the axis has across its labels and returns that maximum. The room is a horizontal axis's height or a vertical axis's width; in a chart, it is the chart's height (for a horizontal axis) or width (for a vertical one) inside its margins. A chart can call the function more than once in a draw, so it should depend only on its argument.

minSizenumber

Minimum size alloted for the space that contains the axis tick labels and title.

onstring

Event listener for the specified brush event typename. Mirrors the core d3-brush behavior.

orientstringDefault bottom

The orientation of the shape.

paddingcalloutvalueDefault 5

Space between the text and the box's edge, in pixels. Defaults to 6.

paddingInnernumberDefault 0.1
paddingOuternumberDefault 0.1
parentunknown

Parent config used by the wrapper.

playButtonbooleanDefault true

Determines the visibility of the play button to the left of the timeline, which cycles through the available periods at a rate set by playButtonInterval.

playButtonConfigrecord

The config Object for the Rect class used to create the playButton.

playButtonIntervalnumberDefault 1000

The interval, in milliseconds, between periods when cycling via the play button. Used only when the chart's duration is 0 (no transition); otherwise playback steps once per duration so each step animates in full.

rangearray.&lt;number | undefined&gt;

Scale range (in pixels) of the axis. The given array must have 2 values, but one may be undefined to allow the default behavior for that value.

rangeBreaksfalse | rangebreakrule | array.&lt;rangebreakrule&gt;Default false

Stretches of time to hide from a time axis (weekends, nights, holidays), so the data closes up around them: one rule or a list of them. "weekends"; {days: [5, 6]} (0 is Sunday); {hours: [17, 9]}, daily, wrapping past midnight (9.5 is 9:30); {values: [date, …]}, whole days; or {bounds: [start, end]}, one range. Rules use local time. A rule's marker draws the break marker at the gap (on by default for bounds only).

renderfunction

Draws the timeline.

reversebooleanDefault false

Whether to flip the axis's direction, so its values run the other way: a horizontal axis from right to left, a vertical one from top to bottom (a Plot's y axis, categories included, normally runs bottom to top, so reversing it lists them from the top). Everything placed on the axis follows it: shapes, tick labels, gridlines, breaks, zooming, and hover badges. Defaults to false.

rotatedTickFormatfunction

Tick formatter for labels drawn rotated (see labelRotation), in place of tickFormat: rotation is decided by measuring the labels this way, so a long label can rotate in a shorter form.

rounding"none" | "outside" | "inside"Default none

How a linear or log axis rounds its domain to "nice" values: "outside" widens each end past the data, "inside" pulls each end in, and "none" keeps it as given. Defaults to "none" on an Axis and "outside" in a Plot. A Plot only rounds the ends a user domain leaves open, unless rounding is set here.

roundingInsideMaxSuffixstringDefault +
roundingInsideMinPrefixstringDefault <
scaleaxisscaleDefault linear

Scale of the axis.

scaleAlignnumberDefault 0.5
scalePaddingnumberDefault 0.5
selectstring | htmlelement | null | undefined

The SVG container element as a d3 selector or DOM element.

Passing null or undefined deliberately leaves the axis unmounted — renderMode("compute") plus select(null) produces a scene-only axis (no detached SVG fallback). This is the formal contract callers in plotPaint use to compute axis layout without mounting DOM.

selectiondate | number | false | array.&lt;number | date&gt;

The current selection. Defaults to the most recent period in the timeline. On a chart it is where the timeline starts, and the chart starts on the same period(s); the viewer's picks replace it.

selectionConfigrecord

Selection style.

shape"line" | "rect" | "circle"Default Line

The shape drawn at each tick: "Line" (the default), "Rect", or "Circle".

shapeConfigrecord

Tick style of the axis.

snappingbooleanDefault true

Toggles the snapping value.

tickFormatfunction

Tick formatter, called with the axis as this. Defaults to the locale's abbreviated number format ("1.5k"), with years printed in full ("1990") when the axis's values are all whole numbers from 1000 through 2999.

tickSizenumberDefault 8
tickSuffixstringDefault normal
tickTooltipstring | false | axistooltipconfig | function

The tooltip shown when a tick label is hovered, in a chart: its text (the same on every tick), a function that receives the tick's value (as tickFormat does) and its index and returns the text, or a tooltip config (as tooltipConfig) whose accessors receive the same. The index counts the axis's labels from the start of its domain (0 is the bottom label of a y axis, the left one of an x axis). Unset (the default) or when the function returns nothing, a label cut short with an ellipsis shows its whole text; false, set or returned, shows no tooltip.

ticksarray.&lt;unknown&gt;

Tick values of the axis.

timeLocalerecord

Defines a custom locale object to be used in time scales. Must include dateTime, date, time, periods, days, shortDays, months, and shortMonths (see d3-time-format).

titlestring

Title of the axis.

titleConfigrecord

Title configuration of the axis.

titleTooltipstring | false | axistooltipconfig | function

The tooltip shown when the axis title is hovered, in a chart: the tooltip's text, a function that receives the title and returns it, or a tooltip config (as tooltipConfig) whose accessors receive the title. Unset (the default) or when the function returns nothing, a title cut short with an ellipsis shows its whole text; false, set or returned, shows no tooltip.

translatefunction

Defines how informational text strings should be displayed. By default, this function will try to find the string in question (which is the first argument provided to this function) inside of an internally managed translation Object. If you'd like to override to use custom text, simply pass this method your own custom formatting function.

widthnumberDefault 400

Overall width of the visualization in pixels.