Skip to content

Instantly share code, notes, and snippets.

@mbostock
Forked from tandu/index.html
Last active February 9, 2016 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mbostock/2983699 to your computer and use it in GitHub Desktop.
Save mbostock/2983699 to your computer and use it in GitHub Desktop.
Manual Axis Interpolation
license: gpl-3.0

D3's axis component supports automatic interpolation; simply change the scale, create a transition, and call the axis. The axis component will automatically create a smooth transition.

However, it's also possible to create a custom tween and redraw the axis synchronously for each frame of the transition. If you wanted to display intermediate ticks for a long-running transition, this might be preferred to the default behavior. This example shows a slow zoom from three years to one day.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
var domain0 = [+new Date(2000, 0, 1), +new Date(2003, 0, 1)],
domain1 = [+new Date(2000, 1, 1), +new Date(2000, 1, 2)];
var x = d3.time.scale.utc()
.domain(domain0)
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(0,200)");
var gAxis = svg.append("g")
.attr("class", "x axis")
.call(xAxis);
transition();
setInterval(transition, 10000);
function transition() {
gAxis.transition().duration(8500).tween("axis", function(d, i) {
var i = d3.interpolate(domain0, domain1);
return function(t) {
x.domain(i(t));
gAxis.call(xAxis);
}
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment