Chart.JS -实现多条形图

c2e8gylq  于 2023-11-18  发布在  Chart.js
关注(0)|答案(1)|浏览(176)

我在我的Angular 9应用程序中实现了Chart.JS。图表没有按预期呈现。

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

vnzz0bqm

vnzz0bqm1#

您需要准备对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
  )
}));

相关问题