gka / chroma.js

JavaScript library for all kinds of color manipulations
https://gka.github.io/chroma.js/
Other
10.1k stars 543 forks source link

classes bug? #224

Closed htrex closed 5 years ago

htrex commented 5 years ago
var palette = ['#9e0142', '#cc344d', '#ea5d47', '#f98e52', '#fdbf6f', '#fee594', '#ffffbf', '#eaf79e', '#bfe5a0', '#89d0a5', '#55afad', '#397fb9', '#5e4fa2']; // 13 colors
var breaks = [0, 1, 4, 7, 13, 17, 23, 29, 36, 40, 49, 57, 70]; // 13 breaks
var data = [0, 1, 2, 3, 4, 5, 6, 7, 11, 13, 14, 15, 16, 17, 22, 23, 27, 29, 34, 36, 38, 40, 49, 56, 57, 68, 69, 70];

var colorScale = chroma.scale(palette).classes(breaks);
var unknownColors = 0;
var knownColors = 0;

for (var i = 0; i < data.length; i++) {
  var color = colorScale(data[i]).hex();
  if (palette.indexOf(color) === -1) {
    unknownColors++;
    console.log('color ' + color + ' not in palette for value ' + data[i]);
  } else {
   knownColors++;
  }
}
console.log(unknownColors + ' unknown / ' + knownColors + ' known');

Running this test I'm receiving unexpected values. When using the same number of palette colors and classes breaks, shouldn't the color output from chroma scale stick to the original colors? It seems there's some kind of approximation in the colors, that's a bug or I'm missing something?

htrex commented 5 years ago

the issue is there also when setting the domain

var colorScale = chroma.scale(palette).domain(breaks).classes(breaks);

gives different colors but many are not in the original palette.

htrex commented 5 years ago

Ok, found, there's no bug here, for 13 breaks I must use 12 colors. Sorry for the dumb question, here's a time saver for similar future questions:

var palette = chroma.scale('Spectral').colors(12); // 12 colors
var breaks = [0, 1, 4, 7, 13, 17, 23, 29, 36, 40, 49, 57, 70]; // 13 breaks
var data = [0, 1, 2, 3, 4, 5, 6, 7, 11, 13, 14, 15, 16, 17, 22, 23, 27, 29, 34, 36, 38, 40, 49, 56, 57, 68, 69, 70];

var colorScale = chroma.scale(palette).domain(breaks).classes(breaks);
var unknownColors = 0;

for (var i = 0; i < data.length; i++) {
  var color = colorScale(data[i]).hex();
  if (palette.indexOf(color) === -1) {
    unknownColors++;
    console.log('color ' + color + ' not in palette for value ' + data[i]);
  }
}
console.log(unknownColors + ' unknown');