Pauline - 11 months ago 89

Javascript Question

I have issues creating a logarithmic scale in d3. The scale works fine if it is set to linear.

This works:

`var myLinScale = d3.scale.linear()`

.domain([0, 100])

.range([50, 1150]);

console.log(myLinScale(71)); //output = 831

However, this doesn't 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?

Answer Source

Change your domain:

```
var myLogScale = d3.scale.log()
.domain([0.1, 100])//domain doesn't include zero
.range([50, 1150]);
console.log(myLogScale(71));
```

`<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>`

The explanation is simple: log(0) is not defined. In base 10, for instance, log(0) is a number `x`

so that 10 raised to the power of `x`

is zero... that number, of course, doesn't exist. The limit, however, when we approach zero from the positive side is minus infinity.

In pure JavaScript:

```
console.log(Math.log(0))//returns "-Infinity"
```

Thus, in JavaScript, `log(0)`

is negative infinity, or minus infinity.

That being said:

a log scale must have either an exclusively-positive or exclusively-negative domain; the domain must not include or cross zero.