Using scales
Setting up your scale
Scales need several things to work
A scale type: such as linear
, sqrt
, quantile
or quantize
A domain: the possible inputs
A range: the possible outputs
Scale types
Let’s pretend we had a value called d.frequency
which was 0-100.
d3.scale.linear()
could be used to position it on the x or y axis, change in input = change in outputd3.scale.linear()
could also be used to color objects in an even change - the closer to 100, the more red, the closer to 0, the more beige.d3.scale.sqrt()
could be used to change the radius based ond.frequency
.d3.scale.quantile()
could be used to color it in buckets based on quartiles (first 25%, next 25%, etc)d3.scale.quantile()
could be used to color it in buckets based on quartiles (d.frequency
0-25 is in a bucket, 25-50 is in another bucket, etc)
Scales where you know the domain
If you know your input and output before you start, you can set it up before you read in your data.
// Coloring based on number of cheeseburgers consumed per day
// I'd like zero cheeseburgers to be `beige` and 30 cheeseburgers to be `red`.
var scale = d3.scale.linear()
.domain([0, 30])
.range(['beige', 'red']);
// Positioning based on GDP per capita
// I'd like 0 GDP to be on the far left, and 30k to be on the right-hand side
var scale = d3.scale.linear()
.domain([0, 60000])
.range([0, width])
Scales where you DON’T know the domain
Sometimes you want to space things out according to the max and min values of your dataset. This takes two steps to set up your scale, and then one to use it.
First you set up the type of scale and the range, but you can’t set the domain because you don’t know the possible inputs
var scale = d3.scale.linear()
.range(['beige', 'red']);
Then you read in your data using queue
or d3.csv
or whatever, and you can ask your data for the maximum value.
// After you've read in your data
// find the max value and add it to your
var max = d3.max(data, function(d) { d.frequency; });
scale.domain([0, max]);
// OR!!!
// After you've read in your data
// find the max value and add it to your
var range = d3.extent(data, function(d) { d.frequency; });
scale.domain(range);