David Banks

Web Developer

Smoothly transitioning axes with D3

21 February 2015D3.jsJavaScriptSVG

This post demonstrates how to smoothly transition D3 axes as an alternative to updating axes with new limits instantaneously.

Smoothly transitioning chart axes in response to data updates or user actions is a nice visual effect, compared to simply updating everything in the blink of an eye.

Say you have a D3 scale object, and a D3 axis object linked to that scale:



var yScale = d3.scale.linear()
	.range([200, 20])
	.domain([0, 10]);

var yAxis = d3.svg.axis()
	.orient("left")
	.scale(yScale);

Lets say you added your axis to your chart as such:



svg.append("g")
	.attr("id", "y-axis")
	.call(yAxis);

Then the standard way of changing the limits instantaneously is:



svg.select("#y-axis")
	.call(yAxis);

To smoothly animate the axis change, do this instead:



svg.select("#y-axis")
	.transition()
	.call(yAxis);

It really is so simple - isn't D3 great!?

See the Pen Smooth transition of D3 axes by David Banks (@dbanksNZ) on CodePen.