Scales

We've already used scales many times -- we had a chant, if you remember; what was that again?

SURPRISE POP QUIZ:

INPUT!: [ ] DOMAIN! [ ] NOT DOMAIN!
OUTPUT!: [ ] RANGE! [ ] NOT RANGE!

If you got INPUT! = DOMAIN! and OUTPUT! = RANGE!, you are totally correct!

The reason we use scales is to avoid math. This makes our code shorter, easier to understand, and more robust, as mistakes in high school mathematics are some of the hardest bugs to track down.

To reiterate a point I've hopefully been hammering home since Chapter 1, Getting Started with D3, ES2017, and Node.js, a function's domains are those values that are defined (the input), and the range are those values it returns.
The following figure is borrowed from Wikipedia:

Here, X is the domain, Y is the range, and the arrows are the functions. We need a bunch of code to implement this manually:

   let shape_color = shape => { 
if (shape == 'triangle') {
return 'red';
} else if (shape == 'line') {
return 'yellow';
} else if (shape == 'pacman') {
return 'green';
} else if (shape == 'square') {
return 'red';
}
};

You could also do it with a dictionary, but d3.scale will always be more elegant and flexible:

 const scale = d3.scaleOrdinal() 
.domain(['triangle', 'line', 'pacman', 'square'])
.range(['red', 'yellow', 'green', 'red']);

Much better!

Scales come in three types: ordinal scales have a discrete domain, quantitative scales have a continuous domain, and time scales have a time-based continuous domain. All scales are found in the d3-scale package, if you're going for the microlibrary approach or want to find its documentation.

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

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