对数刻度返回NaN [英] Logarithmic scale returns NaN
问题描述
我在d3中创建对数刻度时遇到问题.如果将比例尺设置为线性,则效果很好.
I have issues creating a logarithmic scale in d3. The scale works fine if it is set to linear.
这有效:
var myLinScale = d3.scale.linear()
.domain([0, 100])
.range([50, 1150]);
console.log(myLinScale(71)); //output = 831
但是,这不起作用:
var myLogScale = d3.scale.log()
.domain([0, 100])
.range([50, 1150]);
console.log(myLogScale(71)); //output = NaN
对数刻度有什么问题?
推荐答案
新解决方案(使用D3 v5.8)
经过两年多的时间,这个问题终于有了一个基于D3的答案,并不像我在原始答案中所做的那样建议从域中删除0(见下文).
New solution (using D3 v5.8)
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).
由于新的符号比例在D3 v5.8中,基于通过对称日志转换,该域允许为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.
因此,请使用您的域和范围而无需进行任何修改:
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>
甚至更短,使用D3 v5.8中的新比例尺构造器:
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>
更改您的域,使其不包含或不为零:
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>
在上面的演示中,我使用的是1e-6
,即0.000001
.
In the above demo I'm using 1e-6
, which is 0.000001
.
说明:
零的对数未定义(或未定义).例如,在以10为底的log(0)是一个数字x
,因此加到x
的幂的10就是零...那个数字当然不存在.但是,当我们从正方向接近零时的极限是负无穷大.
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. The limit, however, when we approach zero from the positive side is minus infinity.
在纯JavaScript中:
In pure JavaScript:
console.log("Log of 0 is: " + Math.log(0))
因此,在JavaScript中,log(0)
是负无穷大或负无穷大.
Thus, in JavaScript, log(0)
is negative infinity, or minus infinity.
话虽如此,根据 API :
对数标度必须具有一个专有的正值或专有的负值域;该域不得包含零或跨越零. (强调我的)
a log scale must have either an exclusively-positive or exclusively-negative domain; the domain must not include or cross zero. (emphasis mine)
这篇关于对数刻度返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!