Setting Scales, Domains, and Ranges
Learn how to set-up the domains and ranges and how scaling works in D3.
We'll cover the following...
Let’s take a look at the JS code that sets-up the ranges and domains.
Set the ranges and domains
This is another example where, if we set it up right, D3 will look after us forever.
From our basic web page, we have now moved to the section that includes the following lines:
// set the rangesvar x = d3.scaleTime().range([0, width]);var y = d3.scaleLinear().range([height, 0]);
The purpose of these portions of the script is to ensure that the data we ingest fits onto our graph correctly. Since we have two different types of data, date/time and numeric values, they need to be treated separately. However, D3 manages them in almost the same way. To properly examine this whole concept of scales, domains, and ranges, we will also move slightly out of sequence and (in conjunction with the earlier scale statements) take a look at the lines of script that occur later and set the domain. They are:
// Scale the range of the datax.domain(d3.extent(data, function(d) { return d.date; }));y.domain([0, d3.max(data, function(d) { return d.close; })]);
The concept of scaling
The idea of scaling is to take the range of values of data that we have and fit them into the space we have available.
If we have data that goes from 53.98
to 636.23
(as the data we have for close
in our CSV file does) but we have a graph that is 450 pixels high (height = 500 - margin.top – margin.bottom;
), we clearly need to make an adjustment.
Not only that; even though our data goes from 53.98
to 636.23
, that would look slightly misleading on the graph, and it should really go from 0
to a bit over 636.23
. It sounds really complicated, ...