Bar charts are the simplest and most reliable way to compare things. If you have categories and numbers, and you want people to understand the difference between them without decoding a visual puzzle, you use bars. Revenue by month. Product sales. Survey answers. Demographics. Anything where the question is basically “how much?” or “which one is bigger?”
The strength of a bar chart is that it relies on length. Humans are very good at comparing lengths. Longer bar means bigger value. Shorter bar means smaller value. No interpretation layer, no storytelling tricks. Just comparison.
Orientation and reading comfort
The Bar chart supports two orientations: vertical (default) and horizontal. Vertical bars work well for short labels and compact comparisons. Horizontal bars are usually the better default when labels are long or when you want the chart to read like a ranked list.
In horizontal mode, the category axis is on the left and values run along the bottom. In vertical mode, categories sit at the bottom and values are on the right, which matches how most business dashboards place numeric scales.
Data format
Bar expects a simple dataset:
[
{ label: 'Sales', value: 128000 },
{ label: 'Marketing', value: 76000 },
{ label: 'R&D', value: 154000, color: '#1677ff' } // color is optional
]
The library treats label as the category key, so it is used for scale domain, tick labels, and join keys during updates.
An item may also carry a color: that bar is filled with it instead of barColor (see Bar width and color below).
Values may be negative: the scale always includes zero, and bars grow from the zero baseline in both directions — below it in vertical mode, to the left of it in horizontal mode. Useful for P&L by segment, period-over-period changes, and other signed comparisons.
A row whose value is missing or not a number keeps its category on the axis but draws no bar (and no value label).
Bar also supports a time-based mode, vertical only, when you pass { date, value } points instead of categorical { label, value } items:
[
{ date: '2025-01-01', value: 128000 },
{ date: '2025-02-01', value: 142500 },
{ date: '2025-03-01', value: 119000 }
]
Dated rows need the default orientation: 'vertical': horizontal bars have no date axis, so they draw such rows without labels and log one console warning.
In that mode the chart uses a time scale on the X axis, which means it can also expose the built-in timeframe controls:
const chart = new RareCharts.Bar('#chart', {
timeframes: true,
defaultTimeframe: '1Y',
});
chart.setData(data);
Timeframe controls and the navigator apply only to the date-based vertical mode. Categorical rows, stacked series and orientation: 'horizontal' have no date axis: there the chart hides the buttons and the navigator strip, and getView() returns null.
There is a third shape: hand Bar series-major data [{ name, values }] and it switches into the stacked mode — segments per category, an auto-built legend, and a 'percent' variant. See Stacked Bar.
Bar reads the mode from the first row, and the rule is part of its contract — there is no mode option: a first row with a values array is the stacked mode; one with both date and value, the date-based mode; anything else, categories. Every row is then read in that mode, so give setData one shape at a time.
Bar width and color
By default a bar takes a fixed share of the space for its category, or, in the date-based mode, barWidthRatio of the smallest gap between dates. barWidth sets it in px instead: the width of a vertical bar, the thickness of a horizontal one, the whole column of a stacked bar. With categories (and stacked) the bar stays centred in its slot, so the axis labels do not move; in the date-based mode the time axis is inset by half a bar, so the bars and date labels shift inward a little as the width changes. A width larger than the space per category or date is cut to it: neighbouring bars touch but never overlap, which also keeps a fixed width sane on a phone. Anything that is not a positive number is ignored and the default applies.
A row's own color fills that bar; bars without one take barColor, then the theme accent. That is enough to pick out one bar (the current month, a record, an outlier) without a second series:
new RareCharts.Bar('#chart', {
barWidth: 18,
barColor: '#cccccc',
}).setData([
{ label: 'Nov', value: 141000 },
{ label: 'Dec', value: 156000, color: '#1677ff' },
]);
Colors follow the data: setData repaints a bar whose color changed, and a bar that lost its color goes back to barColor. Hover only dims a bar, so its color stays. The stacked mode ignores a value's color: segments always take their series color. Value labels inside horizontal bars are drawn in the theme background color, so a per-bar color should be dark enough to carry them.
In the date-based mode the time axis is inset by half a bar, so the first and last bars sit whole inside the plot.
Showing values on bars
Bars can print their values (showValues: true), with the text from valueFormat and valueOffset px between the bar end and the label. On horizontal bars the label sits past the bar end and flips inside the bar if there is not enough space near the edge of the chart — as long as the label fits inside. A label that fits neither way (a short bar near the edge, often a small negative value) stays outside, and the value axis widens to make room for it; valueInsideGap sets how tight the space must be. On vertical bars (categories and dates) the label sits above a positive bar and below a negative one, and the value axis grows so the labels of the tallest and the deepest bars fit. Where labels would collide — long values on a narrow card — the larger values keep theirs: a label that would come within 6px of a larger one beside it, or cross another bar, is left out, so the peaks stay labelled; the tooltip keeps every value. The record chart above prints its values in thousands, as its axis does. Stacked bars print no values. While the bars grow in, the labels fade in at their places.
This solves a classic annoyance: value labels that collide with the container edge or become unreadable when bars are short.
Long labels (without ruining the axis)
Real category labels are rarely “A, B, C”. They are usually “Dubai Marina - Contract Renewals (Enterprise)”. For that, Bar supports labelMaxLength, which truncates the rendered axis label to a fixed number of characters and adds an ellipsis. Importantly, the full label remains available via tooltip when the label was truncated, so you do not lose information, you just stop the axis from turning into a paragraph. On horizontal bars the left gutter grows to fit the longest label (after labelMaxLength) — never below 65px, at most 40% of the chart width; a label longer than that is cut with an ellipsis and keeps its full text in the tooltip. An explicit margin.left keeps the gutter as given.
This is one of those details you only miss when you do not have it.
Value formatting and units
In vertical mode, the Y axis uses yTickFormat. If you do not provide it, Bar labels the ticks by the step between them — 0 0.5 1 1.5, 145 150 155, SI prefixes from 1,000 on with one prefix per axis (0 0.5M 1M), zero always as 0 — and supports yPrefix and ySuffix for units — in the categorical, date-based and stacked modes alike (a stacked 'percent' axis keeps its own percent labels).
Value labels (valueFormat) and the default tooltip print full numbers (50,000). For the short form everywhere — 50K, 1.2M — see Short numbers on the settings page.
In horizontal mode, the X axis uses xTickFormat (the same default). If your values are money, percentages, or mixed units, pass explicit formatters. The chart will not guess what your business means by “1.2”. In the date-based mode xTickFormat formats the dates instead; by default the format follows the span in view, as on Time Series — '%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.
Tooltips can be customized via tooltipFormat: (d, info) => html, where d is a copy of the row you passed — label as a string, value as a number; in the date-based mode date is a Date and label is '' — with any extra fields, such as color; info holds the role fields every formatter gets — { label, value, color }, in the date-based mode { date, value, color }. By default it shows the label (the date in the date-based mode) and the value with comma formatting.
Built-in timeframe controls
When the bar chart is running in time-based mode, the shared view API is available:
timeframesrenders the built-in range buttons in the chart header.defaultTimeframeselects the initial visible range and active button.navigator: truerenders 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)callsfn([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()orsetView()— unless that call passed{ silent: true }.
Example:
const chart = new RareCharts.Bar('#chart', {
timeframes: ['3M', '6M', '1Y', 'ALL'],
defaultTimeframe: '1Y',
navigator: true,
});
Annotations
The date-based vertical mode takes the same annotations as Line: points and ranges on dates, lines and bands on values, mixed in one array. They are drawn over the bars on the chart’s own scales, follow timeframes, the navigator and setView(), and move with new data. The pointer passes through them, so a bar under a band still shows its tooltip. The full API is on the Annotations page.
new RareCharts.Bar('#chart', {
annotations: [
{ date: '2025-02-01', label: 'Price up' },
// half a month out on each side: the Jun–Aug bars are shaded whole
{ from: '2025-05-16', to: '2025-08-16', label: 'Promo' },
{ value: 500, label: 'Target' },
],
}).setData(data);
Two details are specific to bars:
- A bar is centred on its date, so a range from the first to the last bar’s date covers only half of each end bar. Start and end the range half a period out to shade whole bars.
- Levels never widen the value axis: it spans the data and zero, with a little headroom above the tallest bar (8% of the span, as on Line). A level beyond the axis is not shown, and a band is cut at the edge of the plot.
The chart keeps room above the plot for the date labels (annotationLabelHeight + 4 px); an explicit margin.top wins. Annotations need a date axis: categorical, stacked and horizontal bars do not draw them and log one console warning per chart.
Animation (if you must)
Bar can animate on first render (animate: true by default). The timing is controlled by duration, per-bar delay by stagger, and easing via ease (cubicOut, cubicInOut, or linear). The chart only animates once per instance by design, so it does not turn normal updates into a circus. Stacked segments fade in instead of growing, all together: stagger does not apply there. Renders that land in the middle of the animation — the font load and the first resize right after setData, a later resize or new data — carry it on to the new sizes instead of skipping to the end or starting over.
Hiding axes and grid
Sometimes the cleanest chart is one with less chrome. All three visual layers — grid lines, X axis, and Y axis — can be independently hidden:
showGrid: false // no grid lines
showXAxis: false // no bottom axis
showYAxis: false // no side axis
This is especially useful inside a MultiChart when panels share the same category labels: suppress the Y axis on panels after the first to eliminate duplication and give bars more horizontal room.
Quick example
const d3 = RareCharts.d3; // the d3 bundled with RareCharts
new RareCharts.Bar('#chart', {
orientation: 'horizontal',
height: 260,
labelMaxLength: 18,
showValues: true,
valueFormat: d => d3.format(',.0f')(d.value),
}).setData(data);
Bar chart options
Common options shared by all chart types (title, subtitle, legend, legendPosition, source, note, controls, theme) are documented on the Settings page. A categorical or dated Bar draws one series, so its legend is a caption; the stacked mode's legend hides and shows series (Stacked Bar). For several series over dates, use DualAxes.
| Option | Type | Default | Description |
|---|---|---|---|
Layout |
|||
height |
number | 200 |
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. Width is always 100% of the container. |
margin |
object | vertical {12, 64, 8, 0}, horizontal {12, 0, 16, 65} |
Inner padding {top, right, bottom, left}.The gutter holds the value axis (right, vertical: 64px, as on Line) or the category labels (left, horizontal: 65px at least — it grows to the longest label, up to 40% of the width) and collapses when that axis is hidden; the bottom one collapses with the X axis. With annotations on vertical bars, top grows to annotationLabelHeight + 4 to fit their labels. Each side you set explicitly wins.
|
orientation |
'vertical' | 'horizontal' |
'vertical' |
Bar direction. Horizontal works best for long category labels and ranked lists. |
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. In the date-based mode only. |
timeframes |
boolean | array | — | Built-in timeframe buttons for date-based vertical bars. Pass true to use the default set ['1M', '3M', '6M', '1Y', '2Y', 'ALL']. Categorical, stacked and horizontal bars have no date axis and hide them. |
defaultTimeframe |
string | object | — | Initial active timeframe used when the chart is in date-based mode. |
defaultView |
array | — | Initial visible date range as [from, to] (date-based mode). An explicit alternative to defaultTimeframe; clamped to the data extent. |
navigator |
boolean | object | — | Built-in overview strip with brush selection under date-based vertical bars. Categorical, stacked and horizontal bars hide it. |
Annotations (date-based vertical mode) |
|||
annotations |
array | — | Event markers and reference levels, as on Line: vertical (date, from/to) and horizontal (value, yFrom/yTo) entries in one array. A range spans bar centres; levels outside the value axis are not shown. Categorical, stacked and horizontal bars ignore them with one console warning. See Annotations. |
annotationLabelHeight |
number | 22 |
Pixels reserved above the chart for vertical annotation labels. |
Bar style |
|||
barColor |
CSS color | theme accent | Fill for bars without their own color (single-series modes). |
barWidth |
number | — |
Bar width in px: the thickness in horizontal mode, the whole column when stacked. Overrides the default width and barWidthRatio; with categories the bar stays centred in its slot.Capped at the space per category or date, so neighbouring bars touch but never overlap. Anything that is not a positive number is ignored. |
barWidthRatio |
number | 0.72 |
Bar width as a fraction of the smallest gap between dates in the date-based mode, kept within 2–48px. Ignored when barWidth is set. |
labelMaxLength |
number | — |
Truncate axis labels to N characters and add an ellipsis. The full label is still shown in the tooltip on hover. The horizontal label gutter is measured on the shortened labels. |
Animation |
|||
animate |
boolean | true |
Animate bars on first render. Plays only once per chart instance. Stacked segments fade in instead of growing; value labels fade in at their places. A render in the middle of it (font load, resize, new data) carries it on. |
duration |
number | 650 |
Animation duration in ms. |
stagger |
number | 0 |
Per-bar delay in ms — creates a staggered cascade effect. Categorical and date-based modes; stacked segments fade in together. |
ease |
string | 'cubicOut' |
Easing: 'cubicOut', 'cubicInOut', 'linear'. |
Value labels (horizontal mode only) |
|||
showValues |
boolean | false |
Print numeric labels at bar ends. |
valueFormat |
function | ,.2~f |
(d, info) => string — d is the row, info is { label, value, color }, as for tooltipFormat.Default: ,.2~f — separators, no decimals on a whole number, up to two on a fraction (1,234, 0.4).
|
valueOffset |
number | 6 |
Distance in px between the bar end and the label. |
valueInsideGap |
number | 42 |
Horizontal bars: when space past the bar end is below this px threshold, the label flips inside the bar — if it fits there; otherwise it stays outside and the axis widens to fit it. |
Axis formatting |
|||
yTickFormat |
function | by tick step | (value) => string — Y axis tick labels in vertical mode. Default: by the step between ticks — ,~f below 1,000, SI ~s (one prefix per axis) from 1,000, 0 for zero. |
yPrefix |
string | '' |
Prefix for the default Y labels in vertical mode — categorical, date-based and stacked, not 'percent' (e.g. '$'). |
ySuffix |
string | '' |
Suffix for the default Y labels in vertical mode — categorical, date-based and stacked, not 'percent'. |
xTickFormat |
function | by tick step (dates: by span) | (value) => string — X axis tick labels in horizontal mode, the same default as yTickFormat. In the date-based mode it formats the dates: '%H:%M' up to 36 hours (a tick at midnight names the day), '%b %d' up to 92 days, '%b' up to a year, "%b '%y" up to five years, '%Y' beyond. |
xTicks |
number | 4 (dates: 6) |
Approximate tick count on the X axis: the value axis in horizontal mode, the time axis in the date-based mode. d3 picks round steps; stacked bars divide the axis into exactly this many intervals. |
xTickValues |
array | — | Explicit X tick positions in horizontal mode. |
yTicks |
number | 4 |
Approximate number of Y ticks in vertical mode — d3 picks round steps, so 4 can give 6 marks. Stacked bars divide the axis into exactly this many intervals. |
yTickValues |
array | — | Explicit Y tick positions in vertical mode. Overrides yTicks. |
Visibility |
|||
showGrid |
boolean | true |
Show grid lines. |
showXAxis |
boolean | true |
Show the X axis. Horizontal: numeric (value) axis at the bottom. Vertical: category axis at the bottom. Hiding it also collapses the bottom margin, so the bars run flush. |
showYAxis |
boolean | true |
Show the Y axis. Horizontal: category labels on the left. Vertical: numeric labels on the right. Hiding it also collapses its side margin, so the bars run flush. An explicit margin always wins.
|
Interaction |
|||
tooltipFormat |
function | — |
(d, info) => html where d is a copy of the row: label as a string, value as a number (in the date-based mode date is a Date and label is ''), with any extra fields, such as color; info is { label, value, color } — in the date-based mode { date, value, color } — with color as drawn (formatter arguments). Stacked bars pass a segment — see Stacked Bar.Default shows the label (or the date) and the comma-formatted value. |