I’m trying to get a color according to a metricValue variable (an integer) but the code below is returning the same color #1f77b4. What am I doing wrong?
function getColorForNode(d) {
var p=d3.scale.category10();
var metricValue = metrics.getScore(d.id)
return(p(metricValue)); // Returns the same color independently of metricValue
}
This is related to the fact that no domain was specified for this ordinal scale.
It is true that you don’t need to specify a domain for ordinal scales as described in the docs (https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-ordinal_domain). In that case it will automatically build a domain on the fly while you are using the scale. It keeps track of that domain in the scale instance.
The problem is that in your case you create a new scale instance for each call to getColorForNode. So, there is no persistent domain. Every time it starts from scratch building a domain and it will output the first range value: #1f77b4.
So, there are basically two solutions:
Option 1: keep the scale instance construction outside the function
Option 2: explicitly specify a domain