[英]Logarithmic scale returns NaN
I have issues creating a logarithmic scale in d3.我在 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?对数刻度有什么问题?
After more than 2 years this question finally has a D3-based answer that doesn't suggest removing 0 from the domain, as I did in my original answer (see below). 2 年多之后,这个问题终于有了一个基于 D3 的答案,该答案不建议从域中删除 0,就像我在原始答案中所做的那样(见下文)。
This is possible due to the new Symlog scale in D3 v5.8, based on a by-symmetric log transformation , which allows 0 in the domain.这是可能的,因为 D3 v5.8 中的新Symlog 比例基于对称对数变换,允许域中为 0。
So, using your domain and range without any modification:因此,无需任何修改即可使用您的域和范围:
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:或者更短,使用 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>
Change your domain so it doesn't 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'm using 1e-6
, which is 0.000001
.在上面的演示中,我使用的是1e-6
,即0.000001
。
Explanation:说明:
The logarithm of zero is undefined (or 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.例如,在基数 10 中,log(0) 是一个数字x
因此 10 的x
幂为零……当然,这个数字不存在。 The limit, however, when we approach zero from the positive side is minus infinity.然而,当我们从正侧接近零时,极限是负无穷大。
In pure JavaScript:在纯 JavaScript 中:
console.log("Log of 0 is: " + Math.log(0))
Thus, in JavaScript, log(0)
is negative infinity, or minus infinity.因此,在 JavaScript 中, log(0)
是负无穷大或负无穷大。
That being said, according to the API :话虽如此,根据API :
a log scale must have either an exclusively-positive or exclusively-negative domain;对数标度必须有一个完全正域或完全负域; the domain must not include or cross zero .域不得包含或交叉零。 (emphasis mine) (强调我的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.