Skip to content Skip to sidebar Skip to footer

Javascript/d3: The "same" Function Call Yields Different Result?

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 '#2c

Solution 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.

Post a Comment for "Javascript/d3: The "same" Function Call Yields Different Result?"