MichaelE
MichaelE

Reputation: 767

how to set color for each datapoint in chartjs-chart-treemap

I am producing a treemap with chartjs-chart-treemap v2.0 and chartsjs 3.6. I can't seem to find how to set the color of each box. I wouldexpect to find it here:

.....
 datasets: [{
      tree: Data.statsByState,
      key: 'area',
      groups: GROUPS,
      spacing: 1,
      borderWidth: 0.5,
      borderColor: 'rgba(200,200,200,1)',
      backgroundColor: 'rgba(220,230,220,0.3)',
      hoverBackgroundColor: 'rgba(220,230,220,0.5)',
      captions: {
        align: 'center',
        display: true,
        color: 'red',
        font: {
          size: 14,
        },
        hoverFont: {
          size: 16,
          weight: 'bold'
        },
        padding: 5
      }
    }]

Each datapoint value is handled in 'key' and 'groups', I would expect a similar property in datasets. Would appreciate any help on how to set the colors.

Upvotes: 1

Views: 1132

Answers (1)

MichaelE
MichaelE

Reputation: 767

To control the colors assigned to each rectangle (datapoint) in the treemap. The index for the dataset array is buried in ctx.raw._data._idx. So you can create your own array of colors and assign each datapoint a specific color with:

  datasets.backgroundColor: (ctx)=>this.getColor(ctx)

in getColor

   getColor(ctx) { 
   const colors = [arrray of colors];
   if (ctx.type==='data') {
      return colors[ctx.raw._data._idx];  
   }
  else return 'transparent';
}

Upvotes: 1

Related Questions