[Chartjs]-Chart.js dataset label issue

3👍

It might be easier to achieve what you’d like if you would consider every element in your arroLevelsCount array as a standalone dataset. So the simplest config would look like this (and here’s a JSFiddle of that):

arroChartConfig = {
  type: sChartType,
  data: {
    datasets: [{
      label: arroLevels[0],
      data: [arroLevelsCount[0] ],
      backgroundColor: arroLevelColors[0],
      pointStyle: 'triangle',
    }, 
    {
      label: arroLevels[1],
      data: [ arroLevelsCount[1] ],
      backgroundColor: arroLevelColors[1],
      pointStyle: 'triangle',
    },
    {
      label: arroLevels[2],
      data: [ arroLevelsCount[2] ],
      backgroundColor: arroLevelColors[2],
      pointStyle: 'triangle',
    }],
    labels: arroLevels
  },
  options: {
    tooltips: {
      callbacks: {
        title: function(chart, data) {
          return data.labels[chart[0].datasetIndex];
        }
      }
    }
  }
 }

But if you’d like to stick to your approach there are a few things to consider. The generateLabels option has to be inside of the labels option and the function passes the entire config as a parameter so you can’t just return data.text, instead you have to iterate over the labels. The function generateLabels requires an array legend item as return.

Considering all points above the legend option could look like this:

legend: {
  position: 'right',
  labels: {            
    generateLabels: function(chart) {
        return chart.data.labels.map(function(label, i) {
            return {
                text: label,
                fillStyle: chart.data.datasets[0].backgroundColor[i]
            };
        });
    }
  }
}

Here is your updated JSFiddle.

Edit:
To display the correct tooltip label color for your approach you should add the labelColor callback aswell and return the color depending on the hovered dataset.

labelColor: function(ttitem, data) {
          return {
            borderColor: arroLevelColors[ttitem.index],
            backgroundColor: arroLevelColors[ttitem.index]
          };

This is the second JSFiddle updated with the labelColor callback.

Leave a comment