Scales are functions that map a domain to a range. Yeah, yeah, I keep saying that, but there really isn't much more to say.
The reason we use them 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.
If you haven't just spent four years listening to mathematics at school, a function's domain are those values where it is 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 arrows are the functions.
We need a bunch of code to implement this manually:
var shape_color = function (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...