Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random colors in an specific range using D3?

I am trying to generate random colors in an specific range for the bubbles in my Bubble chart using D3. I wanted the colors to be only in the range of blue and grey. I tried the following code for that:

var domainMax = 20;
var colorFn = d3.scale.linear()
        .domain([0, domainMax])
        .range(['blue', 'grey']);

var randomNum = Math.floor((Math.random() * domainMax));
var color = colorFn(randomNum);

My problem is that the colors generated by this methods are mostly very close to each others and some of them are the same. I played with domainMax and make it smaller and bigger but I did not see any changes. I would appreciate a lot if someone can tell me what method I can use to generate randomly different colors in an specific range.

like image 674
Sahar Avatar asked Oct 21 '25 04:10

Sahar


1 Answers

Let me try something really basic here. If you want a colour that ranges between blue and grey, then for the RGB value, you want R and G to be the same and B to be greater than both. Note that you'll get different shades of grey if R == G == B, so to add a 'blue shade' to this grey, you simply need to raise the value of B.

(Conversely, if you lower B, you'll get various shades of R+G, i.e. yellow)

For example

function getColor(inputValue){
  r = 120;
  b = 120 + (d * 7) % (256-r)
  return 'rgb(' + r + ',' + r + ',' + b + ')' 
}

Here is a fiddle: http://jsfiddle.net/pt3seenj/

The higher the value of R and G, the brighter your blue is. Anyway, you just need to play around with the getColor function to get exactly what you want.

like image 91
Daniel Sutantyo Avatar answered Oct 23 '25 17:10

Daniel Sutantyo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!