Customizing Axes in D3.js

Photo by Isaac Smith on Unsplash


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

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")

Basic customization using the axis generator

xAxis.attr("transform",`translate(${0},${height - 20})`);
let tickLabels = ['A','B','C'];
xAxisGenerator.tickFormat((d,i) => tickLabels[i]);

Inspecting the SVG elements that form an axis

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

Customizing the SVG elements of an axis

<path class="domain" stroke="#000" d="M0.5,-200V0.5H470.5V-200"></path>".domain")
<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>".tick text")
xAxis.selectAll(".tick text")
xAxis.selectAll(".tick line")
.attr("stroke","steelBlue");":nth-child(3) line")




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