使用 Chartjs Angular 按值排序和隐藏图例项

问题描述

如果提供的值为 0,我想隐藏或不显示图例,并按升序排列项目

export class DoughnutChartComponent {

  doughnutChartLabels: Label[] = ['CR1','CR2','CR3','CR4','CR5','Box','APP','Center 8','Center 9'];
  doughnutChartData: number [] = [55,25,20,54,33,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'
    ]
  }] ;
}

有没有可能。因为我没有得到任何解决方案。 感谢帮助

解决方法

这基本上可以通过Array.filter(),然后是Array.sort()来实现。

由于这需要在 doughnutChartLabelsdoughnutChartData 上同时完成,您应该首先将标签和相应的值包装到对象中,并在最后解开这些对象,均使用 Array.map()

为此,您可以将以下 constructor 添加到 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);
}
,

您可以像这样使用由 chart.js 提供的图例标签的过滤器功能:

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","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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...