Upon integrating Chart.js into my Angular 9 application, I encountered an issue where the expected chart values were not being displayed.
In order to address this problem, I need to structure the barChartData
according to the format showcased in this stackblitz Demo.
The API response data is as follows:
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 }
];
To populate the barChartData
with the API response, here is the anticipated dataset structure:
this.barChartLabels = ['Application', 'Customer Care', 'Package'];
this.barChartData = [
{
label: 'OSEN+ Passtive',
type: 'bar',
stack: 'OSEN+',
data: [30, 31, 23],
},
{
label: 'OSEN+ Negative',
type: 'bar',
stack: 'OSEN+',
data: [-15, -16],
},
{
label: 'MBC Passtive',
type: 'bar',
stack: 'MBC',
data: [20, 21],
},
{
label: 'MBC Negative',
type: 'bar',
stack: 'MBC',
data: [-10, -11],
},
];
I have attempted to implement the logic by creating labels and datasets based on the API response:
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 operatorLabels = [];
for (let label of labels) {
datasets.push(
data.find((y) => y.label == label && y.subLabel == x)?.count || 0
);
}
return {
label: operatorLabels,
data: datasets,
};
});
Desired outcome: https://i.sstatic.net/uJ8jz.png