Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 44 ยท Shapes and Paths

Building Bar Charts with D3

Build a complete D3 bar chart step by step: margins, band and linear scales, axes, value labels, sorting.

A bar chart is the "hello world" of D3 because it uses everything you have learned so far: data, a data join, a band scale, a linear scale and two axes. Once you can build one calmly, line charts, scatter plots and heatmaps are variations. This lesson builds a full chart, then shows horizontal and grouped versions.

The recipe

Every D3 chart follows the same five steps.

  1. Dimensions: set width, height and margins, and compute the inner size.
  2. Scales: a band scale for categories and a linear scale for values.
  3. Container: an SVG, and a g translated by the margins.
  4. Marks: a data join of rect elements.
  5. Axes and labels: axes (and titles) appended to the same g.
flowchart LR
  A["1. Dimensions<br/>and margins"] --> B["2. Scales<br/>band + linear"]
  B --> C["3. SVG and<br/>inner g"]
  C --> D["4. Join rects"]
  D --> E["5. Axes and labels"]

The same five steps build almost every D3 chart.

A vertical bar chart

A complete vertical bar chart

Study the details; they repeat in every chart.

  • y(d.users) is the top of the bar (SVG y grows downward), and the height is ih - y(d.users), the distance from the top down to the baseline.
  • .nice() rounds the maximum so the axis ends on a tick.
  • Value labels are placed 5 pixels above the bar with a text-anchor: middle class.
  • The key function d => d.lang keeps bars tied to categories if data changes.

Sorting bars

Bars are easier to compare when sorted. Change the domain order, not the data order of the join (which only matters for the DOM order):

JavaScript
const sorted = d3.sort(data, (a, b) => d3.descending(a.users, b.users));
x.domain(sorted.map(d => d.lang));

Because the join uses keys, the same elements will move to their new x positions when you re-render, which sets you up for a smooth animation in Transitions.

A horizontal bar chart

Long category names read better on the left. Swap the roles of the scales: the band scale goes on y, the linear scale on x, and bars grow from left to right.

Horizontal bars with sorted data

Notice m.left is larger to leave room for the country names that the left axis draws. Always size margins to your labels.

Grouped bars

To compare several series per category (for example two years per country), use two band scales: an outer one for the groups and an inner one within each group's bandwidth for the series.

JavaScript
const x0 = d3.scaleBand().domain(groups).range([0, iw]).paddingInner(0.2);
const x1 = d3.scaleBand().domain(series).range([0, x0.bandwidth()]).padding(0.05);

Then create one g per group translated by x0(group), and inside it one rect per series positioned with x1(series). This is the nested selection pattern from Nested Selections.

Grouped bars with two band scales

The inner join data(d => keys.map(...)) reshapes each row into one object per bar. That reshaping, plus a legend, is where most of the code goes.

Making bar charts honest and readable

  • Start the value axis at zero for bars; a cropped baseline misleads.
  • Sort by value unless the categories have a natural order (months, ages).
  • Label bars directly when you have few, or draw light gridlines when you have many.
  • Leave margin for long labels, or switch to horizontal bars.
  • Add <title> children to the rects (.append("title").text(...)) for a free native tooltip and screen reader text.

Make charts accessible: set role="img" and an aria-label on the SVG, and add a visually hidden data table or <title> elements so non-visual users can reach the numbers. The title element is also free tooltip text.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. For a vertical bar, what are y and height?

    SVG's y grows downward, so the bar's top is y(d.value) and it extends down to the baseline at innerHeight.
  2. 2. How do you sort the bars by value?

    The band scale's domain order determines position. Re-render and keyed bars move to the new positions.
  3. 3. In a grouped bar chart, what is the range of the inner band scale?

    The inner scale distributes the series inside one group's slot, whose width is the outer bandwidth.
  4. 4. Why should a bar chart's value axis start at zero?

    Bars communicate magnitude by length. Truncating the axis distorts comparisons.

Summary

  • Follow the five steps: dimensions, scales, container, join, axes.
  • Bars use x(category), bandwidth(), y(value) and innerHeight - y(value).
  • Sort by changing the band scale's domain; use keyed joins to keep bars tied to categories.
  • Horizontal bars swap the scales; grouped bars use two nested band scales and a reshaped inner join.

Next: Line Charts and Curves