Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 44 ยท Scales and Axes

Axes in D3: Ticks, Labels and Gridlines

Draw axes in D3 with axisBottom, axisLeft, axisTop and axisRight: set ticks, tickFormat and tickSize, add titles and gridlines, restyle with CSS.

An axis tells readers what the positions mean. Hand-drawing tick marks and labels is tedious, so D3 gives you axis generators. You give one a scale, call it on an SVG group, and it draws a line, tick marks and labels, choosing sensible tick values on its own. Axes are components: functions that take a selection and fill it in, which is why you apply them with selection.call(axis).

The four axis generators

Generator Ticks point Labels sit Typical use
d3.axisBottom(scale) down below the line x axis at the bottom
d3.axisTop(scale) up above the line x axis at the top
d3.axisLeft(scale) left left of the line y axis
d3.axisRight(scale) right right of the line secondary y axis

An axis is drawn at (0, 0) in its container, so you translate the group to the right place: the bottom axis goes to translate(0, innerHeight) and the left axis to translate(0, 0) (or translate(margin.left, 0) when not inside the margin group).

JavaScript
g.append("g")
  .attr("transform", `translate(0, ${innerHeight})`)
  .call(d3.axisBottom(x));

g.append("g").call(d3.axisLeft(y));

The generator works with any scale type: linear, time, log, band, point. It uses the scale's ticks() method when there is one, or the whole domain for band and point scales.

Your first axes

The generated markup is ordinary SVG: a path.domain for the axis line, and one g.tick per tick, containing a line and a text. Inspect it in dev tools and you will see you can style it with CSS.

Controlling ticks

Configure an axis by chaining methods before you call it:

JavaScript
d3.axisBottom(x)
  .ticks(5)                    // about 5 ticks (a hint, D3 picks nice values)
  .ticks(d3.timeMonth.every(2)) // for time scales: every 2 months
  .tickValues([0, 25, 50, 100]) // exact ticks
  .tickFormat(d => d + "%")    // change the label text
  .tickSize(8)                 // tick length (default 6)
  .tickSizeOuter(0)            // no end caps on the axis line
  .tickPadding(10)             // space between tick and label

ticks(count) is only a hint: D3 uses nice round values near that count, so you might get 6 ticks when you asked for 5. For exact positions use tickValues. For labels, tickFormat takes a function or a format string such as d3.format(".0%") (see Number and Time Formatting).

Configured axes

Axis titles

An axis has no title. Append a text element yourself, positioned in the margin. For a rotated y label:

JavaScript
g.append("text")
  .attr("class", "axis-title")
  .attr("transform", "rotate(-90)")        // rotate around the origin
  .attr("x", -ih / 2)                      // after rotation, x is the vertical position
  .attr("y", -margin.left + 14)
  .attr("text-anchor", "middle")
  .text("Income (USD)");

Rotating around the origin swaps the axes: after rotate(-90), x runs upward and y runs to the right, which is why the numbers look odd the first time.

Gridlines

Gridlines are just an axis with long ticks and no labels. Build a second axis with tickSize equal to the plot size (negative to point inside) and empty labels, then fade it with CSS:

JavaScript
g.append("g")
  .attr("class", "grid")
  .call(d3.axisLeft(y).ticks(5).tickSize(-iw).tickFormat(""))
  .call(g => g.select(".domain").remove());

Draw gridlines before the data marks so the marks sit on top.

Styling with CSS

Axis parts have stable class names: .domain (the line), .tick, .tick line, .tick text. By default D3 sets fill="none", stroke="currentColor", a font size of 10 and text-anchor directly on the group. Style the parts in a stylesheet or via the .call(g => ...) pattern:

JavaScript
.call(g => g.select(".domain").attr("stroke", "#adb5bd"))
.call(g => g.selectAll(".tick line").attr("stroke", "#dee2e6"))
.call(g => g.selectAll(".tick text").attr("font-size", 12))

A complete chart with everything

A complete scatter chart: scales, axes, grid and titles

A reusable axis helper

Charts repeat the same few lines. Wrap them in a tiny function that follows the D3 component convention (takes a selection, returns nothing):

JavaScript
const xAxis = (g, scale) => g
  .attr("transform", `translate(0,${innerHeight})`)
  .call(d3.axisBottom(scale).ticks(width / 80).tickSizeOuter(0));

g.append("g").call(xAxis, x);

width / 80 is a handy rule of thumb: about one tick per 80 pixels keeps labels from colliding. Next, learn how to format the labels themselves in Number and Time Formatting.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you draw a bottom axis for scale x at the base of the plot?

    Axes are drawn at the origin of the group they are called on, so translate the group and then call the axis generator.
  2. 2. What does axis.ticks(5) guarantee?

    ticks(count) is a hint. D3 chooses nice values near the count.
  3. 3. How do you create gridlines with an axis?

    Long ticks pointing across the plot with empty labels look like gridlines. Style them lightly with CSS.
  4. 4. Why does the y axis title need rotate(-90) and use -ih / 2 for x?

    A transform rotates the element's coordinate system, so the roles of x and y swap for the text's position.

Summary

  • axisBottom, axisTop, axisLeft and axisRight draw axes from any scale; you position the group with a translate.
  • Configure with ticks, tickValues, tickFormat, tickSize and tickPadding before calling the axis.
  • Titles are your own text elements; gridlines are axes with long ticks and no labels.
  • Axis markup is plain SVG with .domain and .tick classes, styled with CSS or .call(g => ...).

Next: Number and Time Formatting