Skip to content

Instantly share code, notes, and snippets.

@sundicide
Forked from mbostock/.block
Created September 22, 2017 07:51
Show Gist options
  • Select an option

  • Save sundicide/592f93e29c8f09c7594a5e7042fbf001 to your computer and use it in GitHub Desktop.

Select an option

Save sundicide/592f93e29c8f09c7594a5e7042fbf001 to your computer and use it in GitHub Desktop.
Axis Styling II
license: gpl-3.0

This example demonstrates the use of post-selection to customize an axis during transitions. After the axis is rendered, its elements (such as text labels, here) are reselected and modified to produce the desired appearance. When transitioning the axis, the post-selection modifies entering, updating and exiting elements. Passing null values to transition.tween cancels default tweens scheduled by the axis in favor of the customized styles.

<!DOCTYPE html>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 0, bottom: 20, left: 0},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var formatNumber = d3.format(".1f");
var x = d3.scaleTime()
.domain([new Date(2010, 7, 1), new Date(2012, 7, 1)])
.range([0, width]);
var y = d3.scaleLinear()
.domain([0, 2e6])
.range([height, 0]);
var xAxis = d3.axisBottom(x)
.ticks(d3.timeYear);
var yAxis = d3.axisRight(y)
.tickSize(width)
.tickFormat(function(d) {
var s = formatNumber(d / 1e6);
return this.parentNode.nextSibling
? "\xa0" + s
: "$" + s + " million";
});
var xGroup = g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(customXAxis);
var yGroup = g.append("g")
.call(customYAxis);
d3.timeout(function() {
y.domain([0, 4e6]);
yGroup.transition().duration(2500).call(customYAxis);
}, 1000);
function customXAxis(g) {
g.call(xAxis);
g.select(".domain").remove();
}
function customYAxis(g) {
var s = g.selection ? g.selection() : g;
g.call(yAxis);
s.select(".domain").remove();
s.selectAll(".tick line").filter(Number).attr("stroke", "#777").attr("stroke-dasharray", "2,2");
s.selectAll(".tick text").attr("x", 4).attr("dy", -4);
if (s !== g) g.selectAll(".tick text").attrTween("x", null).attrTween("dy", null);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment