How to Create and Customize SVG Axes with d3-axis: A Complete Guide
The d3-axis module transforms any D3 scale into a reusable SVG axis generator that produces a <g> element containing a domain path and tick groups, which you render by calling the generator on a D3 selection.
The d3/d3 repository provides the d3-axis module as the standard way to add reference marks to D3 visualizations. This article explains how to create SVG axes, customize their appearance, and handle dynamic updates based on the actual implementation in d3-axis/src/axis.js and the official documentation at docs/d3-axis.md.
Understanding the d3-axis Architecture
The d3-axis module follows a generator pattern. When you invoke one of the four orientation factories—d3.axisTop, d3.axisRight, d3.axisBottom, or d3.axisLeft—you receive a function that encapsulates axis configuration.
Internally, the generator constructs an SVG structure containing:
- A
<path class="domain">representing the axis line - Multiple
<g class="tick">elements, each containing:- A
<line>for the tick mark - A
<text>element for the label
- A
The implementation in d3-axis/src/axis.js sets sensible defaults during construction: tick size of 6 pixels, padding of 3 pixels, and empty tick arguments that defer to the scale's automatic tick generation.
Creating Your First SVG Axis
To render a basic horizontal axis at the bottom of a chart, combine a linear scale with d3.axisBottom.
// Define the scale
const x = d3.scaleLinear()
.domain([0, 100])
.range([20, 680]);
// Create and render the axis
svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(d3.axisBottom(x));
The .call() method invokes the axis generator, which appends the necessary SVG elements to the <g> selection. The generator automatically queries the scale's ticks() method to determine appropriate tick values and uses tickFormat() for number formatting.
Customizing SVG Axis Appearance
The d3-axis module exposes a fluent API for customizing every visual aspect. All configuration methods return the axis generator, enabling method chaining.
Controlling Tick Density and Format
Use .ticks() to specify the approximate number of ticks or a specific time interval, and provide a format specifier as the second argument.
const topAxis = d3.axisTop(x)
.ticks(5, "~s") // 5 ticks with SI-prefix notation (k, M, G)
.tickPadding(12); // Increase space between tick and label
Internally, these arguments are stored and later passed to scale.ticks() and scale.tickFormat() during rendering.
Adjusting Tick Size and Padding
Control the length of tick lines and the domain path ends using tickSize, tickSizeInner, and tickSizeOuter.
svg.append("g")
.call(d3.axisLeft(y)
.tickSizeInner(0) // Remove inner tick lines
.tickSizeOuter(6) // Keep 6px square ends on domain path
.tickPadding(6));
The inner tick size controls the length of the <line> elements inside each tick group, while the outer tick size controls the extension of the domain path beyond the first and last tick.
Specifying Custom Tick Values
Bypass the scale's automatic tick generation by providing an explicit array of values to tickValues().
const yLog = d3.scaleLog()
.domain([1, 1000])
.range([height, 0]);
svg.append("g")
.attr("transform", `translate(${width - marginRight},0)`)
.call(d3.axisRight(yLog)
.tickValues([1, 10, 100, 1000])
.tickFormat(d => `${d}x`));
This is essential for log scales or ordinal scales where automatic tick placement may produce undesirable results.
Handling Axis Orientation and Transitions
The axis orientation is immutable once set. To change from a bottom axis to a top axis, you must create a new generator and re-render.
// Initial bottom axis
const xAxis = d3.axisBottom(xScale);
const g = svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(xAxis);
// Later: switch to top with transition
setTimeout(() => {
const xAxisTop = d3.axisTop(xScale);
g.transition()
.duration(750)
.call(xAxisTop);
}, 2000);
For dynamic updates when the underlying scale changes (domain or range), simply call the axis generator again on the same selection, or use a D3 transition for animated updates. The generator efficiently updates existing DOM elements rather than recreating them.
Summary
- d3-axis converts D3 scales into SVG axis generators through four orientation factories:
axisTop,axisRight,axisBottom, andaxisLeft. - The generator produces a
<g>structure containing a domain path and tick groups, rendered via.call()on a D3 selection. - Customize axes using the fluent API:
ticks(),tickValues(),tickFormat(),tickSize(), andtickPadding(). - Orientation is fixed at construction; changing it requires a new generator instance.
- Update axes dynamically by re-calling the generator on existing selections, optionally wrapped in a transition for animation.
Frequently Asked Questions
How do I change the number of ticks on a d3-axis?
Use the .ticks() method to suggest a count or specific interval. For example, d3.axisBottom(x).ticks(5) requests approximately five ticks. The scale's ticks() method ultimately determines the exact count based on the domain. For precise control, use .tickValues([0, 20, 40, 60, 80, 100]) to specify exact positions.
Can I use d3-axis with band or ordinal scales?
Yes. d3-axis works with any D3 scale that implements ticks() or domain(), including d3.scaleBand, d3.scaleOrdinal, and d3.scalePoint. For band scales, you typically want to use .tickValues() to show only the band centers or edges, since the automatic tick generator may not align with your discrete categories.
How do I remove the domain line from an SVG axis?
Set the outer tick size to zero using .tickSizeOuter(0). Since the domain path's square ends are controlled by the outer tick size, setting it to zero collapses the domain line. Alternatively, you can select the domain path after rendering and remove it: selection.select(".domain").remove().
Why are my axis labels overlapping and how do I fix it?
Overlapping typically occurs with high tick density or long labels. Solutions include: reducing tick count with .ticks(5), rotating labels via CSS transform on the text elements, using .tickFormat() to abbreviate values (e.g., d3.format("~s") for SI prefixes), or staggering labels by selecting every other tick and adjusting its dy attribute.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →