Angular 9中Chart.js堆叠柱状图数据转换问题求助
问题:Angular 9集成Chart.js堆叠柱状图数据转换问题
问题背景
在Angular 9应用中集成Chart.js后,图表未显示预期数据。需要将给定的API响应数据转换为指定格式的barChartData以实现堆叠柱状图。
API响应数据
let data = [ { operatorName: 'MBC', label: 'Application', subLabel: 'Positive', count: 1 }, { operatorName: 'MBC', label: 'Channels', subLabel: 'Negative', count: -1 }, { operatorName: 'MBC', label: 'Customer Care', subLabel: 'Negative', count: -1 }, { operatorName: 'MBC', label: 'Customer Care', subLabel: 'Positive', count: 1 }, { operatorName: 'OSEN+', label: 'Application', subLabel: 'Negative', count: -1 }, { operatorName: 'OSEN+', label: 'Application', subLabel: 'Positive', count: 1 }, { operatorName: 'OSEN+', label: 'Channels', subLabel: 'Positive', count: 1}, { operatorName: 'OSEN+', label: 'Customer Care', subLabel: 'Positive', count: 1 } ];
预期数据集格式
this.barChartLabels = ['Application', 'Channels', 'Customer Care']; this.barChartData = [ { label: 'OSEN+ Positive', type: 'bar', stack: 'OSEN+', data: [1, 1, 1], }, { label: 'OSEN+ Negative', type: 'bar', stack: 'OSEN+', data: [-1, 0, 0], }, { label: 'MBC Positive', type: 'bar', stack: 'MBC', data: [1, 0, 1], }, { label: 'MBC Negative', type: 'bar', stack: 'MBC', data: [0, -1, -1], }, ];
尝试的无效逻辑
let labels = [...new Set(data.map((x) => x.label))]; let operators = [...new Set(data.map((x) => x.operatorName))]; let subLabels = [...new Set(data.map((x) => x.subLabel))]; let subLabelDatasets = subLabels.map((x) => { let datasets = []; let opratorlabes = []; for (let label of labels) { datasets.push( data.find((y) => y.label == label && y.subLabel == x)?.count || 0 ); } //console.log(data) return { label: opratorlabes, data: datasets, }; });
解决方案
之前的逻辑未关联operatorName,无法按运营商分组生成堆叠数据集。正确做法是先按运营商和子标签组合分组,再对应每个主标签填充数据:
// 提取所有唯一的主标签作为图表X轴标签 this.barChartLabels = [...new Set(data.map(item => item.label))]; // 生成运营商+子标签的唯一组合作为分组依据 const groups = [...new Set(data.map(item => `${item.operatorName}_${item.subLabel}`))]; this.barChartData = groups.map(group => { const [operatorName, subLabel] = group.split('_'); // 为每个X轴标签匹配对应数据,无匹配则填0 const datasetData = this.barChartLabels.map(label => { const match = data.find(item => item.operatorName === operatorName && item.label === label && item.subLabel === subLabel ); return match ? match.count : 0; }); return { label: `${operatorName} ${subLabel}`, type: 'bar', stack: operatorName, data: datasetData }; });
代码说明
- 提取所有唯一
label作为X轴标签,保证数据顺序与标签对应 - 通过
operatorName_subLabel组合实现分组,确保每个运营商的正负数据各成独立数据集 - 遍历分组,对每个X轴标签查找匹配数据,无匹配则填充0,保证数据数组长度与标签一致
- 返回符合Chart.js要求的格式,指定
stack为运营商名称,实现同运营商的正负数据堆叠
预期效果

内容的提问来源于stack exchange,提问作者Ramesh S
相关产品推荐
相关产品推荐

