[Chartjs]-Legend for only specific datasets – chart.js

1πŸ‘

βœ…

You can use the filter on the labels of the legend to filter out the datasets you dont want to show in the legend, see example:

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1,
        backgroundColor: 'red'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1,
        backgroundColor: 'blue'
      },
      {
        label: 'dont show this',
        data: [17, 1, 15, 18, 13, 17],
        borderWidth: 1,
        backgroundColor: 'orange'
      }
    ]
  },
  options: {
    plugins: {
      legend: {
        labels: {
          filter: (legendItem, chartData) => (legendItem.text !== 'dont show this')
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
</body>

Documentation: https://www.chartjs.org/docs/master/configuration/legend.html#legend-label-configuration

Leave a comment