JavaScript/D3: The “same” function call yields different result?

坚强是说给别人听的谎言 提交于 2019-12-24 13:30:28

问题


Here is my confusion(jsfiddle-demo) about the category10 function in D3:

> var a = d3.scale.category10()
> a(0)
"#1f77b4"
> a(10) //the expected different color value
"#2ca02c"

If I call directly the returned function of calling category10 , things go like this

> d3.scale.category10()(0)
"#1f77b4"
> d3.scale.category10()(10) //the SAME color! Why?
"#1f77b4"

In my opinion, calling d3.scale.category10()(10) should yield the same value as calling a(10).

What is going wrong here?


回答1:


Each call to d3.scale.category10() returns a new ordinal scale instance, so by calling it like d3.scale.category10()(10) you are using a new instance each time. Each ordinal scale instance can either be explicitly configured with an input domain (mapping input values to output colors), or it can do so implicitly, where it just returns the first color for the first input value, and so on, creating the mapping as you use it.

In your example you're using a new instance with each call, so no matter what value you input, you will get the first color back. Even your earlier examples might lead to some unexpected behavior unless you explicitly configure the input domain. For example:

var a = d3.scale.category10()
a(0)  // => "#1f77b4"
a(10) // => "#ff7f0e"
var b = d3.scale.category10()
b(10) // => "#1f77b4"
b(0) // => "#ff7f0e"

Here's how you can set the input domain to always return the Nth color whenever you input N no matter what order you make the calls:

var a = d3.scale.category10().domain(d3.range(0,10));
a(0)  // => "#1f77b4"
a(1)  // => "#ff7f0e"
a(2)  // => "#2ca02c"
var b = d3.scale.category10().domain(d3.range(0,10));
b(2)  // => "#2ca02c"
b(1)  // => "#ff7f0e"
b(0)  // => "#1f77b4"

BTW, as an aside, even now a(10) returns the same as a(0) but that's because 10 is outside the range [0,10], which starts at 0 and ends at 9, so a(10) is an unassigned input and gets the next color, which happens to be the first.



来源:https://stackoverflow.com/questions/17872201/javascript-d3-the-same-function-call-yields-different-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!