score:3

Accepted answer

D3 ordinal scales don't have invert methods, but you can create your own.

Once I saw a clever alternative using a scaleQuantile, along these lines:

xscale.invert = function(x) {
    var domain = this.domain();
    var range = this.range()
    var scale = d3.scaleQuantize().domain(range).range(domain)
    return scale(x)
};

Then, in your case, just use:

console.log(xscale.invert(2)) // returns c

Here is a demo:

var xscale = d3.scaleBand() // v4
  .domain(["a", "b", "c", "d", "e"])
  .range([0, 5]);

xscale.invert = function(x) {
  var domain = this.domain();
  var range = this.range()
  var scale = d3.scaleQuantize().domain(range).range(domain)
  return scale(x)
}

d3.range(0, 5.2, 0.2).forEach(function(d) {
  console.log(d.toFixed(2) + " corresponds to: " + xscale.invert(d))
})
<script src="https://d3js.org/d3.v5.min.js"></script>

PS: This solution will ignore any padding you have in the scale.


Related Query

More Query from same tag