[Chartjs]-Order and hide items of legend by value with Chartjs Angular

1๐Ÿ‘

โœ…

You can make use of the filter function for the legend labels provided by chart.js like this:

var options = {
  type: 'doughnut',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 0],
      borderWidth: 1,
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    legend: {
      labels: {
        filter: (legendItem, chartData) => {
          const index = chartData.labels.indexOf(legendItem.text)
          return chartData.datasets[0].data[legendItem.index] !== 0
        }
      }
    }
  }
}

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/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

1๐Ÿ‘

This can basically be achieved through Array.filter(), followed by Array.sort().

Since this needs to be done simultaneously on doughnutChartLabels and doughnutChartData, you should initially wrap labels and corresponding values into objects and unwrap these objects at the end, both with Array.map().

To do so, you could add the following constructor to DoughnutChartComponent.

constructor() {
  const tmp = doughnutChartData
    .map((v, i) => ({ l: doughnutChartLabels[i], v: v }))
    .filter(o => o.v > 0)
    .sort((o1, o2) => o1.v - o2.v);
  doughnutChartLabels = tmp.map(o => o.l);
  doughnutChartData = tmp.map(o => o.v);
}

Leave a comment