1

I have the following implementation, it works and functional. I am checking if fname properties are same in the following javascript object, then I assign the same color for these paired objects.

Here is one javascript object sample:

{"value": 10,"series": 1,"category": "LG","fname": "","valueColor": ""},

However, I would like to use more distinguished colors, rather than very similar color, for example in the given fiddle, colors are almost all in green spectrum. Also I do not want to give any color value where value property equals to 0

Here is the core implementation

function colorSpectrum(N) {
    var colorMap = [], inc = 50, start = 1000;
    for (i = start; i < start+N*inc; i+=inc) {
        var num = ((4095 * i) >>> 0).toString(16);
        while (num.length < 3) {
            num = "0" + num;
        }
        colorMap.push("#" + num);
    }
    return colorMap;
}

function process(data){
    var map = {}, colorMap = colorSpectrum(data.length);
    data.forEach(function(item, index){
        if(!map.hasOwnProperty(item.fname)){
            map[item.fname] = colorMap[index];
        }
        data[index].valueColor = map[item.fname];
    }); 

    return data;
}

FIDDLE

casillas
  • 16,351
  • 19
  • 115
  • 215
  • Not sure I understand what is the problem. Can you explain it better? Maybe just show what would you like to achieve. – Shomz Jun 09 '15 at 15:52
  • @Shomz, I would like to assign more distinguished color for my each javascript objects. My current implementation does spread color from white to black. – casillas Jun 09 '15 at 15:58
  • consider using HSL its much easier to get a nice palette http://www.w3.org/wiki/CSS/Properties/color/HSL – Plato Jun 09 '15 at 17:44
  • do you have any sample in javascript ? – casillas Jun 09 '15 at 18:20

2 Answers2

1

Try picking random colors

function colorSpectrum(N) {
    var colorMap = [];
    for (i = 0; i < N; i+=1) {
        var color = getRndColor()
        colorMap.push("#"+color);
    }
    return colorMap;
}

function getRndColor() {
    var n = Math.floor(Math.random()*255*255*255);
    var hex = Number(n).toString(16);
    while(hex.length < 6) {
        hex = "0"+hex;
    }
    return hex;
}
1

If you want a full range of colors from black to white, you need to change this part:

var colorMap = [], inc = 50, start = 1000;
for (i = start; i < start+N*inc; i+=inc) {

You see, the loop starts from 1000, which is the color #3e8, already green. The scale should go from 0 to 4095 (for 3-character values like #007, #abc, etc...), with having the increment based on the amount of data.

However, I'd suggest getting at least a little bit of the control by having all RGB components generated separately instead of the full HEX value right away.

Shomz
  • 37,421
  • 4
  • 57
  • 85