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.
forked from geoffreyammons's block: Axis Styling
xxxxxxxxxx
<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 lowerY = -3, upperY = 3;
var y = d3.scaleLinear()
.domain([lowerY, upperY])
.range([height, 0]);
var xAxis = d3.axisBottom(x)
.ticks(d3.timeYear);
var yAxis = d3.axisRight(y)
.ticks(7)
.tickSize(width)
.tickFormat(function(d) {
return d == 0 ? '' : Math.abs(+d).toString() + ' \u{03C3}';
});
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) {
var colors = {
up: '#3F83D8',
down: '#00D7CA'
}
g.call(yAxis);
g.select(".domain").remove();
g.selectAll(".tick line")
.attr("stroke-width", 2)
.attr("stroke", function(d) { return d == 0 ? "darkgray" : "lightgray"});
g.selectAll(".tick text").attr("x", 4).attr("dy", function(d) {
return d < 0 ? -4 : 12;
});
g.selectAll(".tick:not(:first-of-type)")
.append("rect")
.attr("y", 1)
.attr("height", (height / 6) - 2)
.attr("width", width)
.attr("fill", function(d) { return d >= 1 ? colors["down"] : colors["up"] } )
.attr("fill-opacity", function(d) { return 1 - (Math.abs(d) * .3); });
}
console.log('hi')
</script>
https://d3js.org/d3.v4.min.js