Customizing Axes in D3.js

Photo by Isaac Smith on Unsplash

Introduction

<!doctype html>
<html>
<head>
</head>
<body>
<script src="js/d3.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
const margin = {top: 20, right: 10, bottom: 20, left: 10};const width = 500 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
const g = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

Making a horizontal axis

const min_data = 0, max_data = 10000;let xScale = d3.scaleLinear()
.domain([min_data, max_data])
.range([0, width]);
let xAxisGenerator = d3.axisBottom(xScale);
let xAxis =  g.append("g")
.call(xAxisGenerator);

Basic customization using the axis generator

xAxis.attr("transform",`translate(${0},${height - 20})`);
xAxisGenerator.ticks(3);
xAxisGenerator.ticks(3);
xAxisGenerator.tickValues([3000,5000,9000]);
xAxisGenerator.tickFormat(d3.format(".2s"));
let tickLabels = ['A','B','C'];
xAxisGenerator.tickFormat((d,i) => tickLabels[i]);
xAxisGenerator.tickSize(-200);

Inspecting the SVG elements that form an axis

<path class="domain"></path>
<g class="tick">
<line></line>
<text></text>
</g>

Customizing the SVG elements of an axis

<path class="domain" stroke="#000" d="M0.5,-200V0.5H470.5V-200"></path>
xAxis.select(".domain")
.attr("stroke","#E04836")
.attr("stroke-width","6")
.attr("opacity",".6");
xAxis.select(".domain").remove();
xAxis.select(".domain")
.attr("stroke","#E04836")
.attr("stroke-width","10")
.attr("opacity",".6")
.attr("stroke-dasharray","4");
<g class=”tick” opacity=”1" transform=”translate(141.5,0)”>
<line stroke=”#000" y2=”-200"></line>
<text fill=”#000" y=”3" dy=”0.71em”>A</text>
</g>
xAxis.select(".tick text")
.attr("font-size","20");
xAxis.selectAll(".tick text")
.attr("font-size","20")
.attr("rotate","15")
.attr("font-family","cursive");
xAxis.selectAll(".tick line")
.attr("stroke","steelBlue");
xAxis.select(":nth-child(3) line")
.attr("stroke-width","10");

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store