The d3.axis.tickFormat() Function in D3.js is used to control which ticks are labeled.
This function is used to implement your own tick format function.
Syntax:
axis.tickFormat([format])Parameters:
This function accepts the following parameters.
- format: These parameters are format to set the tick format function.
Return Value:
This function returns the currently set tick format function, which defaults to null.
Example 1: Below programs illustrate the d3.axis.tickFormat() function in D3.js.
<!DOCTYPE html>
<html>
<head>
<title>
D3.js | D3.axis.tickFormat() Function
</title>
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js">
</script>
<style>
svg text {
fill: green;
font: 15px sans-serif;
text-anchor: center;
}
</style>
</head>
<body>
<script>
let width = 400, height = 400;
let svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
let yscale = d3.scaleLinear()
.domain([0, 1])
.range([height - 50, 0]);
let y_axis = d3.axisLeft().scale(yscale)
.tickValues([0, .2, .5, .70, 1])
.tickFormat((d, i) => ['a', 'e', 'i', 'o', 'u'][i]);
svg.append("g")
.attr("transform", "translate(100, 20)")
.call(y_axis)
</script>
</body>
</html>
Output:
Example 2:
<!DOCTYPE html>
<html>
<head>
<title>
D3.js | D3.axis.tickFormat() Function
</title>
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js">
</script>
<style>
svg text {
fill: green;
font: 15px sans-serif;
text-anchor: center;
}
</style>
</head>
<body>
<script>
let width = 600, height = 400;
let svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
let xscale = d3.scaleLinear()
.domain([0, 10])
.range([0, width - 100]);
let x_axis = d3.axisBottom(xscale).ticks(4)
.tickFormat(x => `(${x.toFixed(1)})`);
let xAxisTranslate = height / 2;
svg.append("g")
.attr("transform", "translate(50, "
+ xAxisTranslate + ")")
.call(x_axis)
</script>
</body>
</html>
Output: