scaleQuantize

Get introduced to another important scale in D3.js, scaleQuantize.

We'll cover the following

As mentioned in the previous lessons, in linear and logarithmic scales, input and output are both continuous. When the input is continuous, and the output is discrete, we use the scaleQuantize scale.

scaleQuantize is a variant of linear scale, which has discrete output. The input is continuous and is divided into portions specified by values in the range. The mapping is linear, and the output, y, can be expressed in terms of the input, x, through the following function.

y=mx+cy =mx + c

Example

We are going to demonstrate the scaleQuantize function through an example.

Console
Code of scaleQuantize

Explanation

Let’s dive into the explanation of the above code to understand how it works.

  • Line 2-3: we have defined our domain [0-100], which is continuous in nature, and our range consists of four discrete values.
  • At line 5, we are giving input 5 which will give us the color Neon Carrot on the console.

Different portions of the input are mapped linearly into discrete output and can be seen in the following figure.

invertExtent

Let’s talk about the invertExtent function that will return the portion of input for the corresponding value of the given range of scaleQuantize function. By using the invertExtent, we can find different portions of input, as shown in the above figure.

Let’s dive into the code to see how invertExtent works.

Console
Code of invertExtent

Explanation

See the following explanation to understand the working of the above code.

Line 5-8: We are giving the range of the scaleQuantize function as an input to the invertExtent function, which will print the portion of inputs corresponding to specific values of the discrete range as shown on the output console.