Apex stacked chart bar is not showing in the proper x-axis

192 views Asked by At

I am using the Apex stacked bar chart in my Angular 16 application. Here I have 4 categories in the x-axis, and the bar is not coming in the proper x-axis label.

My API response data:

let data = [
      {
        tenantName: 'OBC+',
        labelName: 'Application',
        total: 85,
        postiveTotal: '21',
        negativeTotal: '-64',
      },
      {
        tenantName: 'Discovery-world',
        labelName: 'Application',
        total: 194,
        postiveTotal: '119',
        negativeTotal: '-75',
      },
      {
        tenantName: 'OBC+',
        labelName: 'Channels',
        total: 40,
        postiveTotal: '0',
        negativeTotal: '-40',
      },
      {
        tenantName: 'OBC+',
        labelName: 'Wifi',
        total: 1,
        postiveTotal: '1',
        negativeTotal: '1',
      },
      {
        tenantName: 'Discovery-world',
        labelName: 'Channels',
        total: 59,
        postiveTotal: '0',
        negativeTotal: '-59',
      },
      {
        tenantName: 'Vidocon',
        labelName: 'Test',
        total: 30,
        postiveTotal: '10',
        negativeTotal: '-20',
      },
    ];

enter image description here

Please check the above image. The API response here tenantName: 'Vidocon', the series data is not coming in the proper x-axis label.

It is supposed to show in the 'Test' x-axis label but it is shown in the 'Application' x-axis label.

Example Code

1

There are 1 answers

3
Yong Shun On BEST ANSWER

For each bar, the data array should contain the values with the size based on your x-axis category.

  1. Split the data with the positiveTotal and negativeTotal fields to two different objects.

  2. Get the categoryGroups which is an array of name values from the newData. Example: "OBC+ Positive", "OBC+ Negative", "Discovery-world Positive" and etc.

  3. Form the subLabels array by iterating the categoryGroups array and form the object with the data based on the above concept.

let newData = data
  .map((x) => [
    {
      labelName: x.labelName,
      group: x.tenantName,
      name: x.tenantName + ' Positive',
      value: x.postiveTotal,
    },
    {
      labelName: x.labelName,
      group: x.tenantName,
      name: x.tenantName + ' Negative',
      value: x.negativeTotal,
    },
  ])
  .reduce((acc, cur) => {
    acc.push(cur[0]);
    acc.push(cur[1]);

    return acc;
  }, []);


let labels = [...new Set(data.map((x: any) => x.labelName))];
let categoryGroups = [...new Set(newData.map((x) => x.name))];

let subLabels = categoryGroups.map((category) => {
  return {
    group: newData.find(x => x.name == category).group,
    name: category,
    data: labels.map(
      (label) =>
        newData.find((z) => z.name == category && z.labelName == label)
          ?.value ?? 0
    ),
  };
});

Demo @ StackBlitz

enter image description here