Angular 9 chart js mutibar

zynd9foi  于 2023-05-17  发布在  Chart.js
关注(0)|答案(1)|浏览(156)

我在我的angular 9应用程序中实现了chart js。预期的图表值没有出现。
ngOnInit:

ngOnInit(): void {

        this.smdashboardservice.fetchSmDashboardData().subscribe(response=>{
      
                //let data = response.data
                let data = [
                        {"label":"Application","sublabel":"Nice","count":2},
                        {"label":"Application","sublabel":"poor","count":1},
                        {"label":"Channels","sublabel":"Quality","count":2},
                        {"label":"Customer Care","sublabel":"support","count":2}
                ]
             
                this.barChartLabels = Object.keys(data);
                this.barChartLabels.forEach(label => {
                        this.barChartData[0].data.push(data[label]['count']);
                });
      
        })
}

当前赋码图

但我期待着这样

Demo here

zwghvu4y

zwghvu4y1#

您需要准备对sublabel进行分类的数据集。
每个数据集应包含x轴类别长度为(label)的值,即3。

let labels = [...new Set(data.map((x) => x.label))];
let subLabels = [...new Set(data.map((x) => x.sublabel))];
let subLabelDatasets = subLabels.map((x) => {
  let datasets = [];

  for (let label of labels) {
    datasets.push(
      data.find((y) => y.label == label && y.sublabel == x)?.count || 0
    );
  }

  return {
    label: x,
    data: datasets,
  };
});

this.barChartLabels = labels;
this.barChartData = subLabelDatasets;

Demo @ StackBlitz
备选方案:subLabelDatasets可以简化为:

let subLabelDatasets = subLabels.map((x) => ({
  label: x,
  data: labels.map(
    (label) =>
      data.find((y) => y.label == label && y.sublabel == x)?.count || 0
  )
}));

相关问题