Reputation: 576
Horrific title, I apologise.
Can someone please help me understand how to achieve the following.
I have a lovely routine that plots a scale, on a map, which is quite customisable in terms of it's orientation, number of colours, etc, the core of which is as follows:
var heatmapColour = d3.scale.linear().domain(d3.range(0, colours.length, 1.0 / (colours.length - 1))).range(colours);
var c = d3.scale.linear().domain(d3.extent(legendDomain)).range([0, 1]);
And if I have an array of colours as the following:
var colours = ["#6363FF", "#6373FF", "#63A3FF", "#63E3FF", "#63FFFB", "#63FFCB", "#63FF9B", "#63FF6B", "#7BFF63", "#BBFF63", "#DBFF63", "#FBFF63", "#FFD363", "#FFB363", "#FF8363", "#FF7363", "#FF6364"];
My routine can generate a legend of Red, Yellow, Green, Cyan and Blue if I set the legendDomain to have 5 entities, or if I set it to 3, would be simply Red, Green, and Blue, etc, etc.
It works perfectly.
However I'm now trying to match some countries to his legend which are based on their order in an array.
So for example, and for simplicity, if I have 50 countries and my legend set to draw 5 colours, I want the first 10 to be Red, the next 10 Yellow, the next 10 Green, etc, etc.
Using the same method to create the legend simply doesn't produce the same results.
Where my legend creates a range of colours within a domain, I now want to kind of go into this backwards and return a colour if 'something' (in this case it's order in the array) falls between the colour values.
Can someone please explain on how to achieve this.
Upvotes: 0
Views: 91
Reputation: 32327
I did something like this:
var colors = ['red', 'green', 'blue', 'brown'];
var countries = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"];
var heatmapColour = d3.scale.ordinal().range(colors);//i used ordinals instead of linear
countries.forEach(function(d, i){
console.log(d,heatmapColour(Math.floor((i)/colors.length)))
});
working code here
Upvotes: 1
Reputation: 1433
A bit long for a comment, but is this what you are trying to achieve?
// Example arrays
var cols = ['c1', 'c2', 'c3'];
var ctry = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function getCol(cols, i) {
return cols[Math.floor(i / cols.length)];
}
ctry.map(function(d,i) { console.log(getCol(cols, i)); });
(essentially divide index by length of color array and floor).
Upvotes: 1