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.
Last active
January 16, 2020 09:06
-
-
Save mbostock/3371592 to your computer and use it in GitHub Desktop.
Axis Styling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 | |
redirect: https://observablehq.com/@d3/styled-axes |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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