Creating a multi-bar chart using Chart.JS

I integrated Chart.JS into my Angular 9 application. However, the chart is not displaying as I expected.

ngOnInit(): void {
  this.smdashboardservice.fetchSmDashboardData().subscribe(response=>{

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

  })
}

The current code displays the chart like this:

https://i.sstatic.net/2uMm7.png

However, I am aiming for a chart that looks like this:

https://i.sstatic.net/PTS4m.png

Check out the demo here

Answer №1

To organize the datasets, it is important to categorize the sublabel.

Ensure that each dataset includes values corresponding to the x-axis categories (label), which in this case is set to 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;

Check out the Demo on StackBlitz

You can simplify the process by using the following alternative for subLabelDatasets:

let subLabelDatasets = subLabels.map((x) => ({
  label: x,
  data: labels.map(
    (label) =>
      data.find((y) => y.label == label && y.sublabel == x)?.count || 0
  )
}));

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

What is the reason behind the ineffectiveness of injection in abstraction?

I am working with an interface export interface Tree {} The base class implements this interface: export class TreeBase implements Tree {} There are several concrete classes that extend the TreeBase: export class TreeLayers extends TreeBase {} export cl ...

Is it possible to incorporate regular React JSX with Material UI, or is it necessary to utilize TypeScript in this scenario?

I'm curious, does Material UI specifically require TypeScript or can we use React JSX code instead? I've been searching for an answer to this question without any luck, so I figured I'd ask here. ...

Adding images to chart labels in vue-chartjs explained

I'm facing a challenge in adding flag icons below the country code labels, and I could really use some guidance. Here is an image of the chart with my current code The flag images I need to use are named BR.svg, FR.svg, and MX.svg, located under @/a ...

Error message: "The property 'ɵunwrapWritableSignal' is not found on the type 'typeof import_modules/@angular/core/core'". Here is how you can troubleshoot this issue in HTML files

Can anyone help me resolve this error that keeps appearing in all my Angular HTML pages? I am using Node version 14.17.4 and Angular version 15. The error message states: Property 'ɵunwrapWritableSignal' does not exist on type 'typeof impor ...

The NGXS state does not get updated when a lazy loaded component is used

Recently, I started experimenting with the new lazy loaded components in Angular 9. I have a stateful component using NGXS with its state being lazy loaded in a module close to the component. However, after the component renders, the store does not update ...

@The value of @Input is consistently undefined

I'm using @Input to pass IDs into a child component, where they are used to filter the data set within that component. <div *ngIf="exerciseLength > 0"> <exercise [course]="Course" [filter-by-exercise-id]=""></exercise> </di ...

Could I possibly incorporate @mui/material into an Angular project?

Is it possible to use npm install @mui/material in Angular? I am new to Angular and unsure if this will work. If not, are there any alternative Angular libraries that offer Material UI compatibility? ...

Tips for showing legend symbols within tooltips on Highcharts

I've encountered an issue with Highcharts that I need help with. In my Highcharts chart, I'm trying to transfer the symbol from the legend to the tooltip. I'm tackling this challenge in two scenarios: Lines: I have two series, one with a ...

Scroll-triggered Angular 4 sliding functionality

I am struggling to achieve the desired effect. I have successfully set up the @HostListener to detect window:scroll events, but I am unsure how to add a CSS class that animates a div to slide up using CSS animations when scrolling. @HostListener('win ...

How to pre-select a value in Angular PrimeNG dropdown on initialization

I am facing an issue with my PrimeNG dropdown in the dashboard page of my app. I want the dropdown to have a value selected when the page loads, specifically the current financial year. However, the current setup is not working as expected. Below is the co ...

Employing Bazel in conjunction with Lerna and Yarn workspaces

It seems that a lot of people are currently utilizing lerna and/or yarn workspace. I'm thinking about either transitioning from them to Bazel, or perhaps integrating them with Bazel in conjunction with an example project for guidance. Take for insta ...

Ensuring the Angular Material bottom sheet (popover) stays attached to the button

Recently, I've been working on an Angular project where I successfully integrated a bottom sheet from Angular Material. However, I encountered an issue when trying to make the opened popup sticky to the bottom and responsive to its position, but unfor ...

Encountering a TypeError while working with Next.js 14 and MongoDB: The error "res.status is not a function"

Currently working on a Next.js project that involves MongoDB integration. I am using the app router to test API calls with the code below, and surprisingly, I am receiving a response from the database. import { NextApiRequest, NextApiResponse, NextApiHandl ...

Arrange items in a single parent Div in flex-column format, aligning them to the left and

In my Angular application, I am experimenting with stacking Bootstrap toast elements in a customized vertical layout. Specifically, I want certain toast elements to be positioned on the left side of the page (using the align-items-start style) and others o ...

Ways to activate a function onInit in Angular version 9

Currently, I have a function that is activated by clicking a button: export class ExhibitorDetailsComponent implements OnInit { @ViewChild(MapInfoWindow, { static: false }) infoWindow: MapInfoWindow openInfo(marker: MapMarker, content) { this.in ...

How can I initialize the value of a dropdown menu in Angular 2?

In order to have the value of "Select an option" in all select boxes, I initially set it for the first one like this: <select class="form-control" [(ngModel)]="selectedPrototypeSelector" (ngModelChange)="onPrototypeChange()"> <option *ngF ...

Navigating UnwrapRefSimple in Vue Composition API and TypeScript: Best Practices

When I utilize reactive objects in Vue Composition API, I encounter Typescript errors relating to UnwrapRefSimple<T>. This issue appears to be specifically tied to using arrays within ref(). For instance: interface Group<T> { name: string ...

What is the best way to retrieve the filepath of a module that is lazily loaded

Here are the routes that I have set up: const routes: Routes = [ { path: 'path1', loadChildren: () => import('./child/child.module').then(r => r.ChildModule), }, { path: 'path2', loadChildren: () =& ...

Translate JSON to TypeScript class. If the property is an object and not present in the JSON, the class should contain an empty object

I am having trouble finding an appropriate title for the issue I am currently facing. Therefore, I will provide a detailed explanation of the problem. I have a class named Model.ts export class Model{ a:ObjA; b:ObjB; c:ObjC; d:string; ...

Angular2 Final: Issue with inline template - incorrect format for number pipes

Problem <h2>{{totalTargetValue | currency:'EUR':true:'2'}}</h2> Issue Error while using inline template: the specified digit info for number pipes is invalid. Do you have any suggestions on how to resolve this error? ...