9

I'm implementing a heatmap in which the cell background color is determined by a d3 color scale. Some of the values are categorical; their value can be of N different arbitrary string-type categories like ["6TH", "7TH", "5TH", "4TH"].

Given a start color d3.rgb("blue") and an end color d3.rgb("red"), how can I construct color scale that maps a discrete domain of strings into a continuous color range?

I tried

var scale = d3.scale.ordinal()
    .domain(["6TH", "7TH", "5TH", "4TH"])
    .rangeBands( [ d3.rgb("blue"), d3.rgb("red") ] );

which obviously doesn't work.

Greg Venech
  • 8,062
  • 2
  • 19
  • 29
amergin
  • 962
  • 1
  • 12
  • 32

3 Answers3

32

First, I would consider using one of the readily-available Colorbrewer scales; see colorbrewer2.org. These are also available as JavaScript and CSS files in D3's git repository; see lib/colorbrewer. For example, if you have four discrete values in your domain, and you want a red-blue diverging scale, you could say:

var color = d3.scale.ordinal()
    .domain(["6TH", "7TH", "5TH", "4TH"])
    .range(colorbrewer.RdBu[4]);

(You'll need a <script src="colorbrewer.js"></script> somewhere before this, too.) Colorbrewer has a variety of well-designed sequential, diverging and categorical color scales.

If you insist on rolling your own color scale, I strongly recommend interpolating in L*a*b* or HCL color space for accurate perception. You can do this using d3.interpolateLab or d3.interpolateHcl. For example, d3.interpolateLab("red", "blue")(.5) returns a color halfway between red and blue.

To compute the colors for your ordinal scale's range, you can use an interpolator, or you might find a temporary linear scale more convenient. For example:

var categories = ["6TH", "7TH", "5TH", "4TH"];

var color = d3.scale.ordinal()
    .domain(categories)
    .range(d3.range(categories.length).map(d3.scale.linear()
      .domain([0, categories.length - 1])
      .range(["red", "blue"])
      .interpolate(d3.interpolateLab)));
mbostock
  • 51,423
  • 13
  • 175
  • 129
  • 1
    Update: D3's Colorbrewer lib has moved to the [d3-scale-chromatic](https://github.com/d3/d3-scale-chromatic) repository. – danasilver Jul 15 '16 at 05:55
3

You have the right idea, you just need to process each R/G/B color channel. For example, in vanilla JavaScript you can do the following:

var a = [255, 0, 0], // First color
    b = [0, 0, 255], // Other color
    bands = 5,       // Bands is the length of your domain
    i, 
    delta = [];      // Difference between color in each channel

// Compute difference between each color
for (i = 0; i < 4; i++){
  delta[i] = (a[i] - b[i]) / (bands + 1);
}

// Use that difference to create your bands
for (i = 0; i <= bands + 1; i++){
  var r = Math.round(a[0] - delta[0] * i);
  var g = Math.round(a[1] - delta[1] * i);
  var b = Math.round(a[2] - delta[2] * i);
  console.log("<div style='background-color: #" + dec2hex(r) + dec2hex(g) + dec2hex(b) + "'>Band " + i + "</div>");
}

// A helper function for formatting
function dec2hex(i) {
  return (i+0x100).toString(16).substr(-2).toUpperCase();
}

According to the d3 documentation, you can extract each color channel using the r, g and b attributes of a color object:

# d3.rgb(color)

Constructs a new RGB color by parsing the specified color string. If color is not a string, it is coerced to a string; thus, this constructor can also be used to create a copy of an existing color, or force the conversion of a d3.hsl color to RGB.

...

The resulting color is stored as red, green and blue integer channel values in the range [0,255]. The channels are available as the r, g and b attributes of the returned object.

So at the top of the example above, you could say:

var myColor = d3.rgb("blue"),
    a = [myColor.r, myColor.g, myColor.b],
...

Does that help?

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
0

You can always chain an ordinal scale and a linear scale.

The first scale will create quantifiable values from your discrete values, and the second scale will interpolate these values on a color scale.

Something like this:

// Your categories
var data = ["6TH", "7TH", "5TH", "4TH"],

  // Define ordinal to linear scale...
  ordinal = d3.scale.ordinal().domain(data).rangePoints([0, 1]),

  // ...and linear to color scale
  linear = d3.scale.linear().domain([0, 1]).range([d3.rgb("blue"), d3.rgb("red")]);

// Now define your artificial 'compound' scale
function scale(d) {
  return linear(ordinal(d));
}

// And then use it on your D3 code
d3.selectAll('div')
  .data(data)
  .enter()
  .append('div')
  .style('background', scale) // <- et voilà ;)
  .text(function(d) {
    return d;
  });
div {
  color: white;
  width: 3em;
  padding: 1em;
  margin: .2em
  text-align: center;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>