jlbriggs
jlbriggs

Reputation: 17791

cal-heatmap - legendColors as array of color values?

I am trying out cal-heatmap, and I want to supply a simple array of the legend colors to use, rather than having to define CSS classes for each color.

So far in my testing this doesn't seem possible?

for example, using:

legendColors : ['rgb(103,0,31)','rgb(178,24,43)','rgb(214,96,77)','rgb(244,165,130)','rgb(253,219,199)','rgb(224,224,224)','rgb(186,186,186)','rgb(135,135,135)','rgb(77,77,77)','rgb(26,26,26)'],

Gives me a scale with 10 steps from the first to the second color, ignoring the rest.

Am I missing something simple in the documentation, or is this not possible?

I know that I can create CSS classes, but I don't want to do that - I need to have a dynamic, variable number of categories, with dynamically created colors.

Upvotes: 0

Views: 649

Answers (1)

Mark
Mark

Reputation: 108512

I looked through the API and source code and it doesn't seem possible. Two thoughts come to mind:

One, fix it after the fact:

 cal.init({
   range: 10,
   start: new Date(2000, 0, 1, 1),
   data: "datas-hours.json",
   onComplete: function() {
     setTimeout(function(){
       ['rgb(103,0,31)','rgb(178,24,43)','rgb(214,96,77)','rgb(244,165,130)','rgb(253,219,199)','rgb(224,224,224)','rgb(186,186,186)','rgb(135,135,135)','rgb(77,77,77)','rgb(26,26,26)']
        .forEach(function(d,i){               
           d3.selectAll("rect.r" + i)
             .style("fill", d);
           });
        }, 10);
  }

I'm not sure why the setTimeout is necessary and this produces an odd "flash" affect as the colors are swapped. Example here.

Another idea is to write the styles on the fly:

var style = document.createElement('style');
style.type = 'text/css';
['rgb(103,0,31)','rgb(178,24,43)','rgb(214,96,77)','rgb(244,165,130)','rgb(253,219,199)','rgb(224,224,224)','rgb(186,186,186)','rgb(135,135,135)','rgb(77,77,77)','rgb(26,26,26)']
  .forEach(function(d,i){
    style.innerHTML += ".q" + i + " {fill:" + d + "; background-color: " + d + "}";
  });
document.getElementsByTagName('head')[0].appendChild(style);

var cal = new CalHeatMap();
cal.init({
  range: 10,
  start: new Date(2000, 0, 1, 1),
  data: "datas-hours.json"
});

Example here.

Not sure I like either of these options, though. You'd probably be better forking the repository, adding what you want and submitting a pull request. Look down at line 3278 and swap out that color scale with your ordinal one.

Upvotes: 1

Related Questions