How domain and range works in D3js

Tweet about this on TwitterShare on LinkedInShare on Google+Share on Facebook

When you are working with Scale functions in D3, there you need a domain and range to map the data values from an input domain to an output range, which means range of possible input data values to range of possible output values.

Below is the basic example to understand the domain and range.

Suppose you have a dataset like [100, 200, 300, 400, 500, 600] and you need to visualize each data to width of one bar into a canvas of 500px width and height. Code will look like as below.

var data = [100, 200, 300, 400, 500, 600],
width = 500,
height = 500;

var scale = d3.scale.linear()
.domain([100, 600])
.range([100, width]);

In the above code, Overall mapping process is happening between domain and range by using scale function. Even you can use multiple scale function into your script. linear() method is one of the most common scale method to map a continuous input domain to a continuous output range. domain method is the input range of data values, which is minimum and maximum value of dataset ([100, 600]) and range method is the output range, where minimum and maximum width value ([100, width]) is used to return a scaled output values into the canvas, that means the data value will not exceed to the canvas.

Finally it’s up to you that how you define the output range to scale your data. Below is the HTML output on the canvas.

scales domain and range

Leave a Reply

Your email address will not be published. Required fields are marked *


× nine = 9