Bar
Overview
A bar chart draws one rectangle per category, with a length proportional to its value. Use it to compare amounts across categories or periods. Bars can be vertical or horizontal, and several bar traces can be grouped side by side, stacked, or overlaid.
Pick a different chart when:
- the values don't start from a meaningful zero (bar length would mislead): use a dot plot;
- x is continuous and the trend matters: use a line chart;
- you have many long category labels: use horizontal bars.
Minimal example
import { createChart } from '@mk7s/holochart';
const chart = createChart(document.getElementById('chart')!, {
data: [{ type: 'bar', x: ['Mon', 'Tue', 'Wed'], y: [12, 18, 7] }],
});Bars grow from zero, both up and down, and the y range always includes zero. The live example adds a negative value, outlines, and rounded corners:
Loading source…
bar/basicData format
xandy: positions and values. For vertical barsxholds the categories (or numbers or dates) andythe values. For horizontal bars (orientation: 'h'), swap them.- Values can be negative. Bars then extend below (or left of) the base.
base,width, andoffsetset each bar's start, thickness (in axis units), and shift. Each takes one value or one per bar. On a date axis,widthis in milliseconds.x0/dx(ory0/dy) give implicit positions when you leave outx(ory). On a date axis,x0is a date anddxis in milliseconds.xperiod(yperiodfor horizontal bars) snaps each position to its period, such as a month ('M1'), placed byxperiodalignment(see monthly bars).textandcustomdata: per-bar labels and extra data for templates.- A
nullorNaNvalue draws no bar. - Categories appear in the order of the data unless the axis sets
categoryorder(see sorted by value).
Variations
Grouped bars
With layout.barmode: 'group' (the default), bar traces at the same position sit side by side. bargap spaces the positions and bargroupgap the bars within a group. Traces that share an offsetgroup share a slot, so a narrow bar can sit in front of a wide one (targets vs actuals).
Loading source…
bar/groupedStacked bars
barmode: 'stack' stacks traces at each position in trace order. layout.barcornerradius rounds only the outer end of each stack. Set barnorm: 'percent' to stack to 100.
Loading source…
bar/stackedPositive and negative stacks
barmode: 'relative' stacks positive values up from zero and negative values down from zero separately, for inflows and outflows.
Loading source…
bar/relativeLabels on bars
texttemplate formats a label per bar with d3 formats. textposition: 'auto' puts it inside when it fits and outside otherwise; 'inside', 'outside', and 'none' force a choice. Inside labels switch between dark and light text to contrast with the bar color.
Loading source…
bar/textStacked bars with totals
A bar label belongs to one segment, so to label the total of each stack, add a scatter trace with mode: 'text' at the totals, textposition: 'top center', showlegend: false, and hoverinfo: 'skip'. Autorange doesn't make room for text, so set the y range with some headroom.
Loading source…
recipes/stacked-totalsSorted by value
Set categoryorder on the category axis to sort it by the bar values, whatever the order of the data: 'total descending' ranks each category by the sum over all traces (stacked or grouped), and 'min', 'max', 'sum', 'mean' and 'median' work the same way, ascending or descending. Ties keep the data order. On horizontal bars, sort the y axis 'total ascending' to put the largest bar on top, because category axes run bottom-up.
Loading source…
bar/sortedHorizontal bars on a log axis
orientation: 'h' turns bars sideways. On a log axis, bars start below the visible range, as in Plotly. Numeric marker.color maps through a colorscale. More in Horizontal bar.
Loading source…
bar/horizontalMonthly bars with periods
When each value covers a period, give its date and the period: xperiod: 'M1' (a number of months, or a length in milliseconds) with xperiodalignment: 'middle' draws each bar in the middle of its month ('start' and 'end' also work, and xperiod0 sets a period boundary). Give a scatter trace the same period to line its points up with the bars. With ticklabelmode: 'period' the month labels sit under their months. Hover shows the date as given, not the aligned position, as in Plotly.
Loading source…
bar/periodPattern fills
marker.pattern hatches bars with lines or dots: shape ('/', '\', 'x', '-', '|', '+', '.'), size, solidity and colors, one for all bars or one per bar. Patterns tell series apart without color, for print and color-blind readers. See Patterns & textures for fill modes and colors.
Loading source…
bar/patterns3D bars
depth extrudes the bars toward the viewer and bevel rounds their edges; layout.view3d shows the plot in perspective (see 3D-native options).
Loading source…
bar/depthStyling
marker.color: one color, one per bar, or numbers mapped throughmarker.colorscale.marker.line.colorandmarker.line.widthfor outlines (white outlines separate stacked segments well).marker.opacityandmarker.cornerradius(pixels or a percentage string such as'30%');layout.barcornerradiussets it for all traces.textfont,insidetextfont,outsidetextfont,textangle,insidetextanchor, andconstraintextfor labels.layout.barmode,bargap,bargroupgap, andbarnormfor how bar traces combine.xaxis.categoryorder(oryaxis.for horizontal bars) andcategoryarrayfor the order of the categories.marker.patternfor hatch pattern fills:shape,fillmode('replace'or'overlay'),fgcolor,bgcolor,fgopacity,sizeandsolidity(see Patterns & textures).
Interactivity
- Hover. Hovering a bar shows its label. With the default
hovermode: 'closest', the bar under the pointer is picked.hovermode: 'x'(or'x unified') shows every trace at that position, which suits grouped and stacked bars. Thin bars keep a 4 px minimum hit size. Usehovertemplatewith%{x},%{y},%{text}, and%{customdata}. - Zoom and pan. Drag to zoom (the default
dragmode), double-click to reset. - Selection. Box and lasso selection select bars; unselected bars fade (style with
selected.marker/unselected.marker). - Click.
chart.on('click', (e) => e.points[0].x)gives the clicked category, for drill-down. - Legend. Click an entry to hide a trace; the remaining stacks and groups re-flow.
3D-native options
Holochart extensions (full bundle), see Extrusion & 2.5D:
depth: extrusion toward the viewer in px, a percentage of the bar width ('60%'), or one number per bar.0(default) draws flat bars.bevel.sizeandbevel.segments: rounded front and side edges.material: Plotly's lighting model (default),flat, or a three.js material type.layout.view3d: the plot area in perspective (tilt,rotation,perspective), with hover, click, zoom and selection still exact on the extruded bars.
Grouped, stacked, relative and horizontal bars, negative values and base all extrude:
Loading source…
bar/depth-groupedPerformance notes
- Bars are instanced rectangles, so the number of draw calls doesn't grow with the number of bars.
- Stacking and grouping run on the CPU in the calc step. Changing a value re-runs the calc for the bar traces on that axis; changing a color only restyles.
- Hover and selection test the bar boxes on the CPU. That is exact and cheap for typical bar counts; for very many thin bars, a line or a histogram (M3) often reads better anyway.
- Labels are text, which is typeset asynchronously. Thousands of labels take longer to appear than the bars themselves; use
textposition: 'none'or labels on the top N only for large data.
Accessibility notes
- Screen readers: the chart is a
<canvas>. The DOM mirror that describes bars to assistive technology is not built yet (planned for M2, see the accessibility guide). Add a caption oraria-label, and consider a visible data table. - Keyboard: Tab moves into the plot area; ← / → then step through the bars and ↑ / ↓ move to the trace above or below, each stop showing its hover label. See the keys.
- Color: bar labels (
texttemplate) carry exact values without relying on color. In stacked bars, keep the segment order the same as the legend and use white outlines between segments. Hatch patterns (marker.pattern) tell series apart without color, for print and color-blind readers: see Patterns & textures.
Attribute reference
See the bar attribute reference for every attribute, its type, and its default. Bar layout options such as barmode and bargap are in the layout reference.
Related charts
- Horizontal bar: ranked categories and long labels
- Line: trends over an ordered variable
- Scatter: lollipop and dot plots, lighter alternatives to bars
Loading source…
recipes/lollipopPlotly migration notes
- Attribute names,
barmodevalues,barnorm, andoffsetgroup/alignmentgroupbehavior match Plotly. - Value-based
categoryorders ('total descending', …) match Plotly, with two small differences:mediansorts numerically (Plotly compares the values as strings), and categories without values sort last formin/max/mean/median.'geometric mean …'is not supported. - Draw order matches Plotly: bars draw below scatter traces whatever their order in
data, and a higherzorder(on bars too) draws a trace on top of lower ones. xperiod,xperiod0andxperiodalignment(and theyones for horizontal bars) work as in Plotly, and also on linear axes (Plotly only aligns periods on date axes).marker.patternmatches Plotly, exceptpattern.path(custom SVG tiles), which is not supported yet; see the differences.- Bar extrusion (
depth,bevel,material) is a planned Holochart extension (M6).