SpyTh SpyTh - 4 months ago 39
Javascript Question

d3 js V4 ordinal scale behaviour

I would like to create an ordinal scale with one to one correspondence between range and domain. I would expect that values/strings that do not belong to the domain would return nothing. Instead I get the following behaviour:

var x = d3.scaleOrdinal().domain(['a', 'b', 'c']).range([10, 20, 30])

Is there any logic behind this behaviour? Maybe I am missing something, but I couldn't find something out there.


That's the expected behaviour of an ordinal scale. Actually, D3 scales (quantitative or qualitative) are made in such a way that you can pass values outside the domain (see my answer here).

If you want to define outputs for unknown inputs, use scale.unknown():

var x = d3.scaleOrdinal()
    .domain(['a', 'b', 'c'])
    .range([10, 20, 30])
    .unknown("not in the scale");

console.log("b is " + x("b"));
console.log("c is " + x("c"));
console.log("f is " + x("f"));
console.log("xyz is " + x("xyz"));
<script src="https://d3js.org/d3.v4.min.js"></script>