D3 Scales
Why scales?
We’re going to use scales in D3 to map out data attributes to visual variables, whether that means numbers to position or size, categories to colors, etc.
Creating scales
In d3, all scales need an input and an output - a domain and a range.
d3.scaleLinear().domain([inputMin, inputMax]).range([outputMin, outputMax])
Exactly what you give the inputs/outputs depends on your scale type and what you’re trying to do.
Scale types
If you read about scales and see
d3.scale.linear()
, you’re looking at D3 version 3 code. Run far in the other direction!
There are more than this, but these are easy to think about for the time being.
d3.scaleLinear()
- Relating a number to position or color
Continuous input, continuous output
- Example: 0-10 maps to 0->100 (5 -> 50)
- Example: 0-10 maps to white->green (5 -> pale green)
d3.scalePoint()
- Spacing out points evenly on an axis
Nominal input, continuous output (evenly spaced)
- Example: [Cat, dog, man] maps to 0->100 (cat -> 0, dog -> 50, man -> 100)
d3.scaleBand()
- Spacing out bars evenly on an axis
Nominal input, continuous output (evenly spaced)
- Example: [Cat, dog, man] maps to 0->100 (with 10-pixel bars, cat takes up 0-10, dog 45-55, man 90-100)
d3.scaleOrdinal()
- Relating a category to another category
Nominal input, Nominal output
- Example: [Republican, Democrat] maps to [red, blue]
d3.scaleSqrt()
- Relating a number to radius of a circle (area)
Continuous input, continuous output
- Example: 0-10 maps to 0->100 radius