Creating an ordinal scale

An ordinal scale maps a discrete value to some other value. A discrete value is something that can't be divided. Previously, we've used values such as numbers that can be divided up and interpolated. Interpolated just means that for any two numbers, we can find other numbers in between them. For instance, given 10 and 5, we can find values between them (6, 8.2, 7, 9.9, and so on). Now, we want to map values that can't be interpolated—the label properties in our dataset (Bob, Sally, Matt, and Jane). What values lie between Bob and Sally? What about between Bob and Matt? There are none. These are just strings, not numerical values that can be divided up and interpolated.

What we want to do is map these discrete values to other values. The following is an example of how to do this with an ordinal scale. Add the following to the bottom of app.js:

var mapper = d3.scaleOrdinal();
mapper.range([45, 63, 400]); //list each value for ordinal scales, not just min/max
mapper.domain(['Bob', 'Sally', 'Zagthor']); //list each value for ordinal scales, not just min/max

console.log(mapper('Bob'));
console.log(mapper('Sally'));
console.log(mapper('Zagthor'));

The previous code should produce the following:

Note that when you are working with ordinal scales, you'll need to list all of the values for both the domain and range. Even if one set is numerical (in the previous case, the range), you'll still have to list each value. If we just listed the min/max for the range, omitting63, D3 would have no idea what value to map Sally to. After all, how close is Sally to Bob,as a value? How close is Sally to Zagth or, as a value? There's no way to calculate that distance, since they're all strings of text, not numbers.

One thing that's surprising is that you can't invert ordinal scales. Remove the previous three console.log() statements and temporarily add the following to the bottom of app.js:

console.log(mapper.invert(45));

The following will be displayed:

D3 can only go in one direction: from domain to range. You can now remove the console.log() statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.228.189