Skip to content

Instantly share code, notes, and snippets.

@martgnz
Last active July 8, 2018 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martgnz/f30ea82bcd25b788b368fd839737024e to your computer and use it in GitHub Desktop.
Save martgnz/f30ea82bcd25b788b368fd839737024e to your computer and use it in GitHub Desktop.
Format last tick across axis transitions
license: gpl-3.0
height: 106
scrolling: no
border: no

You can use a third argument on axis.tickFormat to customise the formatting of the last tick.

There's another example which uses parentNode.nextSibling. Unfortunately, this wasn't working correctly for me across transitions in a React environment.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
margin: 0;
}
</style>
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
var margin = { top: 20, right: 15, bottom: 20, left: 10 },
height = 100 - margin.top - margin.bottom,
width = 960 - margin.left - margin.right;
var x = d3.scaleLinear()
.domain([0, 100])
.range([0, width]);
var xAxis = d3.axisBottom(x)
.tickFormat(function(d, i, ticks) {
return i !== ticks.length - 1 ? d : d + '%';
});
var svg = 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 + ')');
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(' + 0 + ',' + height + ')')
.call(xAxis);
d3.interval(update, 2000);
function update(){
x.domain([0, d3.randomUniform(1, 100)()]);
svg.select('.x.axis')
.transition()
.duration(500)
.call(xAxis);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment