No multiple lables for grouped and stacked bar charts in chartjs

508 Views Asked by At

I'm trying to create a stacked bar chart with groups in chart.js. But I don't want the labels to be there multiple times, instead just one unique label.

Here's the dataset:

datasets: [
{
  label: 'First Label',
  data: [1,2,3],
  borderColor: 'red',
  backgroundColor: 'red',
  stack: '1'
},
 {
  label: 'Second Label',
  data: [1,2,3],
  borderColor: 'green',
  backgroundColor: 'green',
   stack:'1'
},
 {
  label: 'First Label',
  data: [1,2,3],
  borderColor: 'red',
  backgroundColor: 'red',
   stack:'2'
}

As you can see here: Codepen example The label 'First label' is doubled instead of using the same label. I need this, because I have a group of datasets, which are all using the same label names and each label should be there only once. The color would be the same, too. Do you have any idea? The labels filter function seems not to work... I'm using chart.js v3.1.0 Thanks!

1

There are 1 best solutions below

0
On

I found my mistake on my own. The filter function was in the wrong namespace. It has to be in the plugins object like:

plugins: {
  legend: {
   labels: {
      filter: function(item, chart) {
        // Logic to remove a particular legend item goes here
        return item.datasetIndex;
      },
    },
},

}

and not directly in the options object.