Thales Marques
Thales Marques

Reputation: 353

How to hide more than one legend on Chartjs?

How can I hide two labels on a chart with chart js?

Using this code as an example, I want to hide legend 1 and legend 2, but I only can hide one element

const ctx = document.getElementById('chart');
const data = [1, 2, 3, 4, 5, 6, 7, 8];
const chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      // This label is removed in the filter function
      label: 'Legend 1',
      data: [12, 19, 3, 5, 2, 3],
    }, {
      label: 'Legend 2',
      data: [11, 12, 33, 4, 2, 3],
    }, {
      label: 'Legend 3',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: 'rgba(0, 195, 255, 0.2)',
    }]
  },
  options: {
    legend: {
      labels: {
        filter: function(item, chart) {
          // Logic to remove a particular legend item goes here
                    return !item.text.includes('Legend 1');
        }
      }
    }
  }
});

Thank you

Edit 1

Just to be clear, I've found how to hide just one legend, but I want to hide more than one.

Like the images bellow enter image description here

enter image description here

Upvotes: 1

Views: 2948

Answers (3)

Malia Havlicek
Malia Havlicek

Reputation: 31

It took a bit of time to realize for chartjs V3, it's plugins inside options:

options: {
        plugins: {
            legend: {
                labels: {
                    filter: function(legendItem, data) {
                        let label = data.datasets[legendItem.datasetIndex].label || '';
                        if (typeof(label) !== 'undefined') {
                            if (legendItem.datasetIndex >= 3){
                                return false;
                            }
                        }
                        return label;
                    }
                }
            }
        },
    },

Upvotes: 0

Thales Marques
Thales Marques

Reputation: 353

Found the Answer on this link

Basically what I've done is to insert this statement on options:

    legend: {
        labels: {
            filter: function(legendItem, chartData) {
                if (legendItem.datasetIndex === 0 || legendItem.datasetIndex === 1 ) {
                    return false;
                }
            return true;
            }
        }
},   

I believe that solved my problem

Upvotes: 1

neophytte
neophytte

Reputation: 690

Rather than hide them at the options level, hide them at the label level:

    datasets: [{
      label: 'Legend 1',
        hidden: true,
      data: [12, 19, 3, 5, 2, 3],
    }, {
      label: 'Legend 2',
      hidden: true,
      data: [11, 12, 33, 4, 2, 3],

Upvotes: 0

Related Questions