The stacked bar chart in Apex is not displaying correctly on the x-axis

Currently, I am utilizing the Apex stacked bar chart within my Angular 16 project. In this scenario, there are 4 categories on the x-axis, but unfortunately, the bars are not aligning correctly with the x-axis labels.

The data retrieved from my API is as follows:

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',
      },
    ];

https://i.stack.imgur.com/2wzPW.png

Please refer to the image linked above. The issue arises with the API response for tenantName: 'Vidocon', where the series data is not accurately represented in the corresponding x-axis label.

Expectedly, it should display under the 'Test' x-axis label, yet it is currently appearing under the 'Application' x-axis label.

Sample Code

Answer №1

Ensure that the array data for each bar contains values sized according to your x-axis category.

  1. Segment the data into separate objects using the fields positiveTotal and negativeTotal.

  2. Retrieve the array of name values from newData as categoryGroups. For example: "OBC+ Positive", "OBC+ Negative", "Discovery-world Positive", etc.

  3. Iterate through the array of categoryGroups to create the subLabels array, forming objects with the data based on the concept outlined above.

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
    ),
  };
});

See Demo on StackBlitz

https://i.stack.imgur.com/2Ey0C.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize ngClass for every individual section

I have completed the implementation of all UI components, which are visually appealing. Here is the data structure I am using: public filters = [ { tag: 'Year', label: 'year', items: [200 ...

What are some ways to specialize a generic class during its creation in TypeScript?

I have a unique class method called continue(). This method takes a callback and returns the same type of value as the given callback. Here's an example: function continue<T>(callback: () => T): T { // ... } Now, I'm creating a clas ...

Is there a way to update the text of a button when it is clicked?

Is there a way to dynamically change the text of a button when it is clicked and revert back to its original text when clicked again? I have attempted something along these lines, but I am unsure how to target the text since there isn't a property si ...

Using TypeScript for Immutable.js Record.set Type Validation

Currently, I'm utilizing Immutable.js alongside TypeScript for the development of a Redux application. In essence, the structure of my State object is as follows: const defaultState = { booleanValue: true, numberValue: 0, } const StateRecord = ...

Trouble arises when trying to import Jest with Typescript due to SyntaxError: Import statement cannot be used outside a module

Whenever I execute Jest tests using Typescript, I encounter a SyntaxError while importing an external TS file from a node_modules library: SyntaxError: Cannot use import statement outside a module I'm positive that there is a configuration missing, b ...

Typescript - optional type when a generic is not given

I am hoping for optionalFields to be of type OptionalFieldsByTopic<Topic> if a generic is not provided, or else OptionalFieldsByTopic<T>. Thank you in advance for the assistance. export interface ICreateItem<T extends Topic = never> { // ...

Uniting 2 streams to create a single observable

I am in the process of merging 2 different Observables. The first Observable contains a ShoppingCart class, while the second one holds a list of ShoppingItems. My goal is to map the Observable with shopping cart items (Observable<ShoppingItems) to the i ...

Material-UI Alert: The property `onKeyboardFocus` for event handling is unrecognized and will not be applied

Here is a more detailed trace of the issue: warning.js:33 Warning: Unknown event handler property `onKeyboardFocus`. It will be ignored. in div (created by IconMenu) in div (created by IconMenu) in IconMenu (created by DropdownMenu) in div ...

Using Typescript allows for the possibility of invoking a function with an incorrect parameter type

In the world of software development, there exists a function with the following signature: const validate = (input?: string) => void Behold, there is a Component with props type: type ValidateButtonProps = { onClick: () => void; } And lo, anothe ...

Trying to access @PreAuthorize with the role 'ROLE_ADMIN' is resulting in a Forbidden error

When restricting access to a method for only admins, one can make use of @PreAuthorize("hasRole('ROLE_ADMIN')"). Below is an example implementation: @CrossOrigin(origins="http://localhost:4200") @RestController @RequestMapping("/api/v1") public ...

Combining subscriptions in Angular

For the ngOnInit of a specific component, I have a need to subscribe to two different actions: To make a get request using an already existing Angular service that will return a list of items (sourceOptions in the code). To retrieve the route.queryParams ...

Issue with Angular Compilation When Importing Library Function into Web Worker

I am facing an issue with a web worker in Angular that used to function properly in the previous versions: /// <reference lib="webworker" /> import { ParseResult } from "papaparse"; import { readCSV } from '@fireflysemantics/ ...

Using Typescript: accessing all properties from a specified type while excluding one

Currently working in React, I am interested in extending my type from another, with the exception of some props. This is how I want to approach it : import React from 'react'; import { withTheme } from 'styled-components'; import SvgBa ...

Creating a new line in the content of a MatDialog in Angular 7

I have a situation where I am using MatDialog and attempting to insert a new line in the content definition. I've tried using both \n and </b>, but neither of them seem to work. Is there an alternative way to achieve this without manually e ...

What is the correct way to specify the type in my functional component?

I was trying to define the type in my component in a different way, I know it can be done using classes but is there a way to achieve this with functional components without exporting the interface? Despite my extensive research, I couldn't find any r ...

Display an HTML image within a span tag and ensure it is aligned to the bottom

I am facing a layout issue with 2 images that are placed side by side within their tag . The sizes of the images are different, but they are both anchored at the top of their parent element. <span style="position: relative; left: 0; top: 0; vertical- ...

Attempting a second filter of the table using the dropdown results in no data being returned

I've developed a CRUD app using Angular 7, and I'm facing an issue. When I select a dropdown item for the first time, it shows the desired table data. However, on selecting another item for the second time, it returns nothing. Below is my compone ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

Exploring the world of Vue and Pinia: managing and accessing data like

While delving into Vue and Pinia, I encountered a data management issue on the user side. On my main page, I showcase categories and auction items. However, upon navigating to a specific category in the catalog, the data for auction items remains in the st ...

Tips on transitioning a Node.js application from JavaScript to TypeScript incrementally

I have a JavaScript node application that has grown quite large and I am considering migrating to TypeScript for faster development and easier code maintenance. I have installed TypeScript along with the node and mocha types using the following commands: ...