Search⌘ K

Setting Scales, Domains, and Ranges

Explore how to set up scales, domains, and ranges in D3 for both time and linear data types. Understand how these settings map real data values to graph dimensions, enabling you to create well-proportioned and readable visualizations. Learn the coordinate system's impact on axis direction and the use of d3.extent and d3.max to define data domains accurately.

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:

JavaScript (JSX)
// set the ranges
var 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:

JavaScript (JSX)
// Scale the range of the data
x.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, so let’s simplify it a bit.

First, we make sure that any quantity we specify on the x-axis fits onto our graph.

var x =
...