Chartjs hide dataset legend v3
Asked Answered
G

2

9

My current graphs on the webpage are powered by Chart.js v2.5.3. Charts that were configured a while ago works perfectly fine. Here is the code:

var ctw = document.getElementById("chart-budget");
var myChart = new Chart(ctw, {
  type: 'bar',
  data: {
    labels: ["budget", "costs"],
    datasets: [{
      label: "Amount",
      data: [520980, 23397.81],
      backgroundColor: [
        'rgba(143, 211, 91, 0.2)',
        'rgba(255, 99, 132, 0.2)',
      ],
      borderColor: [
        'rgba(143, 211, 91,1)',
        'rgba(255, 99, 132, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    legend: {
      display: false
    },
    responsive: true,
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        },
        gridLines: {
          drawBorder: false,
        }
      }],
      xAxes: [{
        gridLines: {
          display: false,
        }
      }]
    }
  }
});         

            

As v3 is now available I was thinking to switch to it. A quick test revealed some issues I will need to overcome. One of the issue I'm struggling with is unability to hide dataset legend. In V2.5 it was done by options.legend.display set to false but not any longer. In the documentation I did not come across anything that could help me.

Is there anyone who can advice on how to hide a legend in Chart.js V3?

/Kuba

Groceryman answered 4/4, 2021 at 16:17 Comment(3)
Can you try configuring these options? options: { plugins: { legend: { display: false }, } }Gilford
@Gilford That's exactly it, if you post that as an answer it should be acceptedSpoon
Thanks @noppa, moved it to answer.Gilford
G
27

Configuring option like below would solve the problem in V3 version.

options: { plugins: { legend: { display: false }, } }
Gilford answered 26/10, 2021 at 10:13 Comment(1)
confirmed this works with Chart.js 4.3 (despite what their documentation says)Albarran
B
3

In Chart.js V3 you can add a filter function to options.plugins.legend.labels and evaluate either the labels or their datasetIndex values to suppress specific legends rather than ALL of them.

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;
        }
      }
    }
  }
}
Beanstalk answered 6/6, 2022 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.