Search code examples
angulartypescriptchart.jsdonut-chart

Order and hide items of legend by value with Chartjs Angular


I want to hide or not display legend if the value supplied is 0, and order items in ascending order

export class DoughnutChartComponent {

  doughnutChartLabels: Label[] = ['CR1', 'CR2', 'CR3', 'CR4', 'CR5', 'BOX', 'APP', 'Center 8', 'Center 9'];
  doughnutChartData: number [] = [55, 25, 20, 0, 54, 33, 0, 70, 88];
  doughnutChartOptions: ChartOptions = { legend: {
      display: true,
      position: 'right',
      fullWidth:false,
      reverse: false,
      labels: {
        usePointStyle: true,
        boxWidth: 10,
        padding: 7,
        fontSize: 18,
        fontColor: '#003457',
        fontStyle: 'bold',
      },
      },
     cutoutPercentage: 70,
    };
  doughnutChartType: ChartType = 'doughnut';
  doughnutChartColor: Colors[] = [{
    backgroundColor: [
      '#2E9FE0',
      '#9CCA32',
      '#255FCC',
      '#B746A6',
      '#FF9232',
      '#03B075',
      '#E5D844',
      '#45D2E4',
      '#E0489A'
    ]
  }] ;
}

Is it possible. as i didn't get any solution for this. Thank for help


Solution

  • 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>