Logarithmic scale returns NaN

I am having problems creating a logarithmic scale in d3. The scale works fine if it is set to linear.

It works:

var myLinScale = d3.scale.linear() .domain([0, 100]) .range([50, 1150]); console.log(myLinScale(71)); //output = 831 

However, this does not work:

 var myLogScale = d3.scale.log() .domain([0, 100]) .range([50, 1150]); console.log(myLogScale(71)); //output = NaN 

What is wrong with the logarithmic scale?

+6
source share
1 answer

New solution (using D3 v5.8)

After more than 2 years, this question finally received an answer based on D3, in which it is not proposed to remove 0 from the domain, as I did in my original answer (see below).

This is possible thanks to the new Symlog scale in D3 v5.8, based on an asymmetric log conversion that allows 0 in the domain.

So, using your domain and range without any changes:

 var myLogScale = d3.scaleSymlog() .domain([0, 100]) .range([50, 1150]); console.log(myLogScale(71)); 
 <script src="https://d3js.org/d3.v5.min.js"></script> 

Or even shorter, with the new scale constructors in D3 v5.8:

 var myLogScale = d3.scaleSymlog([0, 100], [50, 1150]); console.log(myLogScale(71)); 
 <script src="https://d3js.org/d3.v5.min.js"></script> 

Original answer (for D3 v3)

Change your domain so that it does not include or cross zero:

 var myLogScale = d3.scale.log() .domain([1e-6, 100])//domain doesn't include zero now .range([50, 1150]); console.log(myLogScale(71)); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

In the above demo, I am using 1e-6 , which is 0.000001 .

Explanation:

The logarithm of zero is not defined (or not defined). For example, in the database, 10 log (0) is the number x so 10 raised to the power of x is equal to zero ... of course, this number does not exist. However, the limit when we approach zero on the positive side is minus infinity.

In pure JavaScript:

 console.log("Log of 0 is: " + Math.log(0)) 

So in JavaScript, log(0) has negative infinity or minus infinity.

This, as they say, according to the API :

the logarithmic scale must have either an exclusively positive or an exclusively negative domain; the domain must not include or cross zero . (my emphasis)

+10
source

Source: https://habr.com/ru/post/1012057/


All Articles