Skip to content

Dual Axes Charts

Sometimes you need to plot two things on the same timeline that simply do not belong to the same scale. Revenue and headcount. Inflation and GDP. Price and spread. If you force them onto one axis, one series becomes unreadable, and the chart turns into a polite lie.

A dual-axis chart solves this by keeping a shared X axis (time) while providing two independent Y axes, so each metric is shown in its natural units. The goal is not to pretend the metrics are comparable. The goal is to compare when they move and how their dynamics relate.

In RareCharts, DualAxes is exactly that: a time-based chart with two vertical scales.

To illustrate a real-world use case, this example uses a finance-native story: a convergence (arbitrage) strategy based on the idea that two similar instruments that temporarily diverged in price will later converge again.

One concrete version of this story exists in government bonds, where a newly issued “on-the-run” Treasury can trade slightly richer than the previous “off-the-run” issue for a period of time. Traders may position for convergence by going long the cheaper issue and hedging the richer one, expecting the price gap to compress as the market normalizes.

In the chart, the right axis (Y1) shows the price index of the two instruments over time. The left axis (Y2) shows the spread between them. Prices and spread are different categories, so they get different axes. The chart stays readable, and the relationship stays visible.

Axis behavior and formatting

Both axes are configured independently. You can set titles (y1Title, y2Title), control tick formatting (y1TickFormat, y2TickFormat), and, when needed, override the visible ranges (y1Domain, y2Domain) to keep the chart stable and comparable across screenshots, reports, or multiple panels.

Axis titles are meant to be terse units (PRICE, N · K HLX). A title that would run past its axis margin is trimmed with an ellipsis — measured by rendered width, so a short label that fits is left alone — with the full text on hover and a one-time console hint. Set axisTitleMaxLength to cap it explicitly, or widen margin if you need more room.

In this example, the spread axis uses a signed format and treats very small values as clean zero, so you do not get the infamous +0.00 noise that makes charts look broken even when the data is fine. Without one, y2TickFormat labels as Line does: ticks by their step (0.5, 65k), end labels and tooltip values with three significant digits.

Logarithmic scale

Each axis has its own scale: y1Scale and y2Scale take 'linear' (default) or 'log', and setYScale(type, { axis }) switches 'y1', 'y2' or 'both'. scaleToggle adds a Log toggle pinned to the top right of the header, above the Y-axis labels, filled while the axis is logarithmic; onScaleChange(fn) reports every switch. A worked example — a long-horizon index on a log Y1 next to a signed yearly change on Y2 — is on the Combined page.

Bands

A series with type: 'band' draws a ribbon on its axis, as on Line: { name, type: 'band', axis: 'y1', values: [{ date, lower, upper }] } — a forecast range, a min–max envelope. It sits behind the bars and the lines (opacity fillOpacity, else areaOpacity, else 0.12), its axis fits both edges, the crosshair reports its range, and the legend toggles it by name. End labels, markers and the navigator leave it out.

Interaction

Dual Axes supports cursor inspection through a crosshair and a tooltip. The tooltip is fully customizable through tooltipFormat: ({ date, points }) => html, so you can present values in your product’s language instead of whatever generic tooltip someone thought was “good enough”.

Legend

The header legend is not built from the series: pass it, and every item that names a series (by series, else name, else label) hides and shows it. Each axis then fits its own series still shown. An axis whose series are all hidden keeps their range, so its labels stay in its units, and the bars left re-pack in their slots while the time axis stays put. legendRescale: false keeps both axes on every series; setSeriesVisible(names | null) sets the legend from code. More: Interactive legend.

Built-in timeframe controls

Because DualAxes is inherently time-based, it can also render the shared timeframe switcher in its own chart header:

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

chart.setData(series);

Available pieces:

  • timeframes renders the built-in range buttons in the chart header.
  • defaultTimeframe selects the initial visible range and active button.
  • navigator: true renders the built-in overview strip with a brush under the main chart.
  • setView([start, end]) sets any custom visible date window.
  • getView() returns the currently visible [start, end].
  • setTimeframe(key, { silent }) selects a timeframe from code, as a button click does.
  • onViewChange(fn) calls fn([start, end]) (Dates, clamped to the data; a window entirely outside the data is passed as given) after every view change — a button, the end of a navigator drag, setTimeframe() or setView() — unless that call passed { silent: true }, so external UI stays synchronized.
  • scaleToggle adds a Log toggle, pinned right in the same header row, above the Y-axis labels (see Logarithmic scale above).

Example:

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

Dual-axis charts are often implemented as a hack: two scales, mismatched formatting, confusing labels, and tooltips that quietly mix units. This component exists to make the dual-axis case predictable, explicit, and safe for real reporting: independent scales, consistent structure, and controlled formatting.

Annotations

DualAxes supports the full annotation API — vertical date markers (point and range) and horizontal reference levels (line and band) on either Y axis. Horizontal entries take an explicit axis: 'y1' | 'y2' so the value is mapped to the correct scale. See the dedicated annotations page for the full API.

Dual Axes 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 280 Chart height in px, the whole card: title, legend, timeframe buttons, navigator and footer come out of it, and the plot gets what is left. On a narrow card they wrap and take more, so leave the plot room.
margin object {10, 64, 18, 64} Inner padding {top, right, bottom, left}.
Right and left default to 64 to give both axes room; a hidden axis collapses its side (see showY1Axis, showY2Axis, showXAxis). Top grows to 30 with y1Title or y2Title, and to annotationLabelHeight + 4 with annotations.
Each side you set explicitly wins — margin.top too.
xPad number 8 Gap in px between the plot edge and the outermost mark on both ends of the X scale.
With bars, the scale is inset by half the widest bar or cluster, so the first and last bars are drawn whole and xPad is the gap to their outer edge; lines start and end at the bar centres.
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 — Built-in timeframe buttons rendered in the chart header. Pass true to use the default set ['1M', '3M', '6M', '1Y', '2Y', 'ALL'], or pass a custom array.
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.
navigator boolean | object — Built-in overview strip with brush selection under the chart. Pass true for defaults or an object with overview options. The strip draws the first line series (or the first series when all are bars); its brush spans every series.
Right axis — Y1

Y1 is drawn on the right side.

y1Domain [min, max] auto Override the Y1 scale domain — used as given, not rounded. On a log axis it needs 0 < min < max; otherwise the auto domain is used.
Useful for keeping charts comparable across snapshots.
y1Scale 'linear' | 'log' 'linear' Y1 scale type. 'log': power-of-ten ticks, multiplicative margin, values ≤ 0 on Y1 skipped, bars from the bottom of the axis. Switch with setYScale(type, { axis: 'y1' }).
y1Ticks number 4 Approximate tick count on Y1 — d3 picks round steps; a log axis uses powers of ten. The auto domain is rounded to the same count, so more ticks hug the data closer (y1Ticks: 10 on 12…87 gives 10…90, not 0…100).
y1TickFormat function as Line (log: .3~s) (value) => string — Y1 tick labels, also used for the Y1 end labels and tooltip values. By default ticks are labelled by their step, as on Line (65k, 0.5), end labels and tooltip values with three significant digits (1.23k).
y1LabelsOnly boolean true Show only tick labels; suppress the axis line.
y1Title string — Axis title, rendered along the right edge.
Left axis — Y2

Y2 is drawn on the left side. Grid lines and the zero baseline are keyed to Y2.

y2Domain [min, max] auto Override the Y2 scale domain — used as given, not rounded. On a log axis it needs 0 < min < max; otherwise the auto domain is used.
y2Scale 'linear' | 'log' 'linear' Y2 scale type. 'log': power-of-ten ticks, multiplicative margin, values ≤ 0 on Y2 skipped, bars from the bottom of the axis. Switch with setYScale(type, { axis: 'y2' }).
y2Ticks number 4 Approximate tick count on Y2 — d3 picks round steps; a log axis uses powers of ten. The auto domain is rounded to the same count.
y2TickFormat function as Line (log: .3~s) (value) => string — Y2 tick labels, also used for the Y2 end labels and tooltip values; the default as for y1TickFormat.
y2LabelsOnly boolean true Show only tick labels; suppress the axis line.
y2Title string — Axis title, rendered along the left edge.
X axis
xTickFormat function by span (date) => string — X tick labels. With the default format a view of a few days gets at most one tick per day, so a date is never repeated.
Lines
curve string 'linear' D3 curve type for line series: 'linear', 'monotone', 'step', etc.
curveTension number 0 Tension for the 'cardinal' curve, 0–1.
strokeDash string — SVG stroke-dasharray applied to all line series globally.
area boolean false Fill area under line series.
areaOpacity number 0.12 Area fill opacity.
areaBaseline 'zero' | 'min' | number 'zero' Area baseline anchor.
Bars
barOpacity number theme barOpacity (0.35) Bar fill opacity. Falls back to the theme’s barOpacity.
barWidth number — Bar width in px for every bar series; with 'cluster', the width of each bar. Overrides barWidthRatio; a series' own barWidth overrides it.
Capped at the smallest gap between bar dates: an overlapping bar is cut to it, a cluster is narrowed to fit it, so neighbours touch but never overlap. Anything that is not a positive number is ignored.
barWidthRatio number 0.65 Bar width as a fraction of the smallest gap between bar dates (the whole cluster with 'cluster'). Ignored when barWidth is set.
barGrouping 'overlap' | 'cluster' 'overlap' How multiple bar series are arranged. 'overlap' centres every bar on its date; 'cluster' places them side by side, each at its own width, the group centred on the date.
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.
showY1Axis boolean true Show the Y1 axis on the right. The right margin collapses once endLabels is off and no y1Title is set — they all share that gutter. An explicit margin always wins.
showY2Axis boolean true Show the Y2 axis on the left. The left margin collapses unless a y2Title is set.
End labels and markers
endLabels boolean true Show the last value of each line series on endLabelsAxis at the right edge (bar series are not labelled).
endLabelsAxis 'y1' | 'y2' 'y1' Which axis’s line series get end labels; they are placed and formatted on that axis. With the default 'y1', Y2 series have none.
markers boolean false Point markers at each data sample on line series.
markerShape string 'circle' Marker shape: 'circle', 'square', 'diamond', 'triangle', 'cross'.
markerSize number theme markerSize (4) Marker radius in px. Falls back to the theme’s markerSize.
Interaction
scaleToggle boolean | 'y1' | 'y2' | 'both' | 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 drives Y1, 'y2' the left axis, 'both' both (filled while either is logarithmic); or { axis, labels: { log } }, labels.log being its text. Each switch fires onScaleChange({ scale, axis }).
crosshair boolean true Vertical tracker with dots at data points and a tooltip on hover.
tooltipFormat function — ({ date, points }) => html — where points is [{ name, series, axis, type, color, date, value, fmt }], one per series covering the hovered date; fmt is the value through that axis’s tick format. All formatters: formatter arguments.
Annotations
annotations array — Event markers and reference levels. Horizontal entries accept axis: 'y1' | 'y2' to choose the scale. See Annotations.
annotationLabelHeight number 22 Pixels reserved above the chart for vertical annotation labels (top margin annotationLabelHeight + 4); an explicit margin.top wins.
Animation
animate boolean true Animate on first render, once per chart instance: lines draw in, bars grow. A render in the middle of it (font load, resize) carries the motion on to the new geometry instead of restarting it.
duration number 650 Animation duration in ms.
ease string 'cubicOut' Easing: 'cubicOut', 'cubicInOut', 'linear'.
Per-series fields

Each object in the series array passed to setData():

name string 'Series N' Series name — shown in the tooltip (the legend is not built from series; pass legend). Also the key that matches lines and bars across setData, so keep names unique.
axis 'y1' | 'y2' 'y1' Which Y axis to plot against.
type 'line' | 'bar' 'line' Rendering type for this series.
color CSS color theme palette Series color.
barWidth number chart barWidth Bar width in px for this series (bars only). Overrides the chart-level barWidth; an invalid value falls back to it.
strokeWidth number theme strokeWidth (2) Line thickness in px (lines only).
strokeDash string — SVG dash pattern for this series only.
curve string global curve Curve override for this series.
area boolean global area Fill area under this series.
areaOpacity number global areaOpacity Per-series area opacity.
areaBaseline string | number global areaBaseline Per-series area baseline.
markers boolean global markers Point markers on this series (lines only); false hides them when the global markers is on.
markerShape string global markerShape Marker shape (lines only): 'circle', 'square', 'diamond', 'triangle', 'cross'.
markerSize number global markerSize Marker radius in px (lines only).
markerFill CSS color series color Marker fill color (lines only).
markerStroke CSS color theme background Marker outline color (lines only).
values array — [{date, value}, ...] — the data points; a point with a missing value (null, '') is dropped.