Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active January 16, 2020 09:06
  • Star 2 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/3371592 to your computer and use it in GitHub Desktop.
Axis Styling
license: gpl-3.0
redirect: https://observablehq.com/@d3/styled-axes

This example shows how to customize the appearance of d3-axis using post-selection: modifying the contents of the SVG elements created by the axis. This technique can also be applied during transitions.

<!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";
});
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(customXAxis);
g.append("g")
.call(customYAxis);
function customXAxis(g) {
g.call(xAxis);
g.select(".domain").remove();
}
function customYAxis(g) {
g.call(yAxis);
g.select(".domain").remove();
g.selectAll(".tick:not(:first-of-type) line").attr("stroke", "#777").attr("stroke-dasharray", "2,2");
g.selectAll(".tick text").attr("x", 4).attr("dy", -4);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment