In this post we will take look at basics of scales in d3.js. and understanding their underlying work and concept.

So what does scale do? Scale as it name says it scales,

scales what? -> the input domain,

to what? -> the range

Let talk in simple terms, you have some collection of numbers, lets say even numbers from 0 to 10 i.e (0,2,4,6,8,10), this collection is known as domain and you want to plot these point on some line say having length of 360px, that should be easy, as line would start from 0 and length upto 360, so the range becomes (0,360)

Like these

Here we have plotted 6 points(0,2,4,6,8,10) on the line of 360px in length,so that pixel distance of 60px is denoting 2 unit i.e 30 px for 1 unit.

This points to pixel mapping was easy, this would not be the case always. Say for example you want to plot (505, 999, 1311, 1750, 1893 ) on line of length 385px, now you are understanding the complexity, and this kind of data you would plot in real application, now how to decide how many pixels should be used to plot above domain, so here d3.scale comes handy.

The mapping of one set of numbers to other is known as Interpolation. D3 scales uses interplation of mapping data points to pixels, to understand more about interpolation go to this article. Beside this scale also offer few more things that you would need for plotting points, axes etc.

There are three types of scales -

• Quantitative

• Ordinal

• Time

Here we will talk about Linear scale which is of type Quantitative scale

Lets say we have following data set { [3,7], [5,10], [10,20], [33,45], [67,98] } , These point [x,y] can be plotted on two dimensional system i.e X-axis & Y-axis. Scale should be calculated separatly for x and y axes. And lets say X axis is of length 370px and Y axis is of 440px

Set of all x co-ordinates [3,5,10,33,67] & set of all y co-ordinates [7,10,20,45,98]

• So for x -

Now set the domain i.e input set of values (Give array of lowest and highest value in set x)

And the range for x axis

Now the magic should happen :)

For input value of 3 I should get 0 on X-axis (lowest pixel value), lets see, try

And for input value 67 I should get 370 (highest pixel value),

Try any other value in between 3 to 67 and output should be between 0 to 370

Similarly for Y axis

Try

Ok I hope this makes the use of scale clear to you, but now how do we use it to plot the axes, and actual points and what are further usage of the Scale, that we will seee in next article.