Logarithmic Scale

Get a brief introduction to the logarithmic scale and take a look at some examples.

We'll cover the following

Introduction

Let’s dive into another important scale, the logarithmic scale. It is similar to the linear scale, except that a logarithmic transformation is applied to the input when it is mapped into the output. The logarithmic scale maps continuous input to continuous output through the following function:

y=mlog(x)+by= mlog(x) + b

where x is the input and y is the output.

As log(0) is equal to negative infinity, the domain of the logarithmic function should include zero. It will show NAN if we pass a negative value as the domain consists of only positive values.

Example

Let’s see how the logarithmic scale works through an example. As we know, logarithmic behavior is shown by algorithms in computer science that divide problems into subproblems and join the solutions of subproblems.

For example, the binary search requires log2(N)log_2(N) steps to find a number in an array of size N. Let’s code this logarithmic function to see it’s working.

Console
Logarithmic scale code

Now we are going to explain the above code to understand it’s working.

  • Line 1-4: we have defined a b_step logarithmic scale. We are setting the domain from 0 to 1048576 using the domain() function. The range is defined from 0 to 20 using the range() function. The default base for the logarithmic scale is 10 in D3.js. Using the base() function, we can change our base to the desired base, in this case,2.
  • In line 5, we can show the number of steps required to find a specific number in an array through binary search on the console. Further, we have used the Math.ceil function to take the ceiling value of the output. As we can see from the console, it takes 17 steps to find 100000 in the range.